我有这个对象数组:
this.clients=[{firstName:"Tywin", lastName:"Lannister", age:46, id:2},
{firstName:"Arya", lastName:"Starck", age:46, id:-1},
{firstName:"John", lastName:"Snow", age:46, id:12},
{firstName:"Robb", lastName:"Starck", age:46, id:24}];
这个变量:
var idArr;
我需要迭代抛出数组中的所有对象并获取所有id并从中创建数组。就像那样:
idArr = [2,-1,12,24]
如何使用lodash实现它?
答案 0 :(得分:5)
使用 Array#map
方法
this.clients=[{firstName:"Tywin", lastName:"Lannister", age:46, id:2},
{firstName:"Arya", lastName:"Starck", age:46, id:-1},
{firstName:"John", lastName:"Snow", age:46, id:12},
{firstName:"Robb", lastName:"Starck", age:46, id:24}];
var idArr = this.clients.map(function(v){ return v.id; })
console.log(idArr);