我有一个对象数组如下:
var GOM = [{name:"Kuroko",ability:"misdirection"},
{name:"Kise",ability:"perfect copy"},
{name: "Akashi", ability: "emperor's eye"}];
是否可以使用lodash中的某些预定义函数或本机javascript(不是forEach)将其拆分为2个数组。
["Kuroko","Kise","Akashi"] and ["misdirection","perfect copy","emperor's eye"]
我知道我可以这样做:
var names = [];
var abilities = [];
GOM.forEach(function(member){
names.push(member.name);
abilities.push(member.ability);
});
但我正在寻找另一种方式。
答案 0 :(得分:4)
将map(),values()和unzip()合并到一个包装器中:
var wrapper = _(GOM).map(_.values).unzip();
然后很容易抓住名字:
wrapper.first()
// → [ "Kuroko", "Kise", "Akashi" ]
和能力:
wrapper.last()
// → [ "misdirection", "perfect copy", "emperor's eye" ]
答案 1 :(得分:3)
Array.map()
适用于此:
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);

答案 2 :(得分:2)
你拥有的代码很好,但是如果你正在寻找更多的东西,那就是功能性的,"始终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" ]
答案 3 :(得分:2)
看起来没有什么比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>