How can I split an array of objects into multiple normal arrays, where each array is filled with one property value?
I have an array of objects like this:
var GOM = [{name:"Kuroko",ability:"misdirection"},
{name:"Kise",ability:"perfect copy"},
{name: "Akashi", ability: "emperor eye"}];
Is it possible to split it into 2 arrays using some predefined function in lodash or native javascript (not for Each).
["Kuroko","Kise","Akashi"] and ["misdirection","perfect copy","emperor 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.
+3
source to share
4 answers
It looks like there is nothing shorter than two coming off lodash:
var data = [
{name:"Kuroko",ability:"misdirection"},
{name:"Kise",ability:"perfect copy"},
{name: "Akashi", ability: "emperor 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>
+2
source to share
Combine map () , values ββ() , and unzip () into a wrapper:
var wrapper = _(GOM).map(_.values).unzip();
Then it's easy to get the names:
wrapper.first()
// β [ "Kuroko", "Kise", "Akashi" ]
And abilities:
wrapper.last()
// β [ "misdirection", "perfect copy", "emperor eye" ]
+4
source to share
Array.map()
works well for this:
var GOM = [{name:"Kuroko",ability:"misdirection"},{name:"Kise",ability:"perfect copy"},{name: "Akashi", ability: "emperor eye"}];
var names = GOM.map(function(item) {
return item.name;
});
var abilities = GOM.map(function(item) {
return item.ability;
});
alert(names + '\n' + abilities);
+3
source to share
Your code is fine, but if you are looking for something more "functional", always reduce
:
var GOM = [ { name: "Kuroko", ability: "misdirection" },
{ name: "Kise", ability: "perfect copy" },
{ name: "Akashi", ability: "emperor 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 eye" ]
+2
source to share