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:
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...
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
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})));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.