使用lodash从对象数组创建int数组

时间:2016-06-11 16:44:57

标签: javascript lodash

我有这个对象数组:

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实现它?

1 个答案:

答案 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);