2017-07-14 91 views
0

例如,假设我有一个数组的几个用户对象:如何使用Lodash keyBy从用户对象中获取用户ID - >标题?

[{name: "Bob", ID: "123", location: "Texas"}, 
{name: "Jill", ID: "124", location: "New York"}, 
{name: "Jan", ID: "125", location: "Alabama"}] 

,我希望得到公正的ID,并把它们放在一个新的阵列,将在其他地方获取其他一些变量,但相应的如:

[{ID: "123", title: "Engineer"}, 
{ID: "124", title: "Architect"}, 
{ID: "125", title: "Manager"}] 

我该如何用Lodash实现?

回答

2

如果解决方案必须以所有方式使用lodash,则忽略此项。
否则......

这可以用Array.prototype.map()

var persons = [ 
 
    {name: "Bob", ID: "123", location: "Texas"}, 
 
    {name: "Jill", ID: "124", location: "New York"}, 
 
    {name: "Jan", ID: "125", location: "Alabama"} 
 
]; 
 

 
var result = persons.map(function(person) { 
 
    return { 
 
    ID: person.ID, 
 
    title: "" /* get title */ 
 
    }; 
 
}); 
 

 
console.log(result);

完成
相关问题