如何从具有过多属性的对象数组中获取“极简”对象数组

问题描述

我有一个数组,像这样:

let x = [
    {id: 1,name: 'A',age: 34.. lots of other properties},{id: 2,name: 'B',age: 17.. },{id: 3,name: 'C',age: 54.. }
]

我怎样才能从中得到这个输出

let output = [
    {id: 1,name: 'A'},name: 'B'},name: 'C'}
]

我的意思是,我可以遍历它,并将新对象推送到新数组中。但我在想是否有更好的方法来做到这一点..

解决方法

更一般地说,对于任何属性集,这个想法在 lodash 和下划线中被称为“pick”和“pluck”...

let x = [
    {id: 1,name: 'A',age: 34 },{id: 2,name: 'B',age: 17 },{id: 3,name: 'C',age: 54 }
]

function pick(object,...attributes) {
  const filtered = Object.entries(object).filter(([k,v]) => attributes.includes(k))
  return Object.fromEntries(filtered);
}

function pluck(array,...attributes) {
  return array.map(el => pick(el,...attributes))
}

console.log(pluck(x,'id','name'))

,

您可以使用.map

let x = [
    {id: 1,age: 34.,},age: 17.,age: 54.,}
];
console.log(x.map(({id,name}) => ({id,name})));