简体   繁体   English

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

[英]How to get a "minimalist" array of objects from an array of objects with a pletora of attributes

I have an array, like this:我有一个数组,像这样:

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

How can I get this output from it:我怎样才能得到这个 output :

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

I mean, I can iterate throut it, and push new objects into a new array.我的意思是,我可以遍历它,并将新对象推入一个新数组。 But I was thinking if there's a better way to do it..但我在想是否有更好的方法来做到这一点..

More generally, for any set of attributes, the idea is called “pick” and "pluck" in lodash and underscore...更一般地,对于任何一组属性,这个想法在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'))

You can use .map您可以使用.map

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM