简体   繁体   中英

How to split an array of objects into multiple normal arrays where each array is populated by one property's values?

I have an array of objects as follows:

var GOM = [{name:"Kuroko",ability:"misdirection"},
           {name:"Kise",ability:"perfect copy"},
           {name: "Akashi", ability: "emperor's eye"}];

Is it possible to split it into 2 arrays using some predefined function in lodash or native javascript(not forEach).

["Kuroko","Kise","Akashi"] and ["misdirection","perfect copy","emperor's eye"]

I know I can just do this:

var names = [];
var abilities = [];
GOM.forEach(function(member){
  names.push(member.name);
  abilities.push(member.ability);
});

but I am looking for another way.

Combine map() , values() , and unzip() into a wrapper:

var wrapper = _(GOM).map(_.values).unzip();

Then it's easy to grab the names:

wrapper.first()
// → [ "Kuroko", "Kise", "Akashi" ]

And abilities:

wrapper.last()
// → [ "misdirection", "perfect copy", "emperor's eye" ]

Array.map() works well for this:

 var GOM = [{name:"Kuroko",ability:"misdirection"},{name:"Kise",ability:"perfect copy"},{name: "Akashi", ability: "emperor's eye"}]; var names = GOM.map(function(item) { return item.name; }); var abilities = GOM.map(function(item) { return item.ability; }); alert(names + '\\n' + abilities); 

The code you have is just fine, but if you're looking for something more "functional," there's always reduce :

var GOM = [ { name: "Kuroko", ability: "misdirection" },
            { name: "Kise", ability: "perfect copy" },
            { name: "Akashi", ability: "emperor's eye" } ];

var result = GOM.reduce(function(memo, member) {
  memo.names.push(member.name);
  memo.abilities.push(member.ability);
  return memo;
}, { names: [], abilities: [] });

console.log(result.names);
// => [ "Kuroko", "Kise", "Akashi" ]

console.log(result.abilities);
// => [ "misdirection", "perfect copy", "emperor's eye" ]

Looks like there is nothing shorter then two pluck's from lodash:

 var data = [ {name:"Kuroko",ability:"misdirection"}, {name:"Kise",ability:"perfect copy"}, {name: "Akashi", ability: "emperor's eye"} ]; var names = _.pluck(data, 'name'); var abilities = _.pluck(data, 'ability'); alert(JSON.stringify(names, null, 4)); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.js"></script> 

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