简体   繁体   中英

flatten object to array in javascript

I want to transform an object like this:

[
  { name: 'john', surname: 'doe' },
  { name: 'jane', surname: 'dee' },
]

Into an array, like this. By choosing an arbitrary key (eg: 'name')

[ 'john', 'jane' ]

What is the fastest way to achieve this? Thanks in advance.

Try use map function like this

[
    { name: 'john', surname: 'doe' },
    { name: 'jane', surname: 'dee' },
].map(function(a){return a.name;})    

If you don't need retro compatibility (and I think you're not going to need it, since you're on NodeJS), you can simply use:

var obj = [
    { name: 'john', surname: 'doe' },
    { name: 'jane', surname: 'dee' },
],
    names = obj.map(function(item) {return item.name;});

Or, the "slowest" way:

var names = []; //obj defined before
for(var i = 0; i < obj.length; i++) 
    names.push(obj[i].name);

If you are using UnderscoreJS , you can simply write:

names = _.pluck(obj, '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.

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