一个例子可以说明一切:
对象数组:
[{
userId: 'ab4e3870-287e-11e7-b5a1-abb6183e9866',
email: 'email1@hotmail.com'
},{
userId: 'ae149220-2883-11e7-bbf9-1fb134f2b4ad',
email: 'email2@hotmail.com'
}]
对象
{
'ab4e3870-287e-11e7-b5a1-abb6183e9866': { name: 'john', roles: 'detective'},
'ae149220-2883-11e7-bbf9-1fb134f2b4ad': { name: 'james', roles: 'plumber'},
}
我想要的结果是:
[{
userId: 'ab4e3870-287e-11e7-b5a1-abb6183e9866',
email: 'email1@hotmail.com',
name: 'john',
roles: 'detective'
},{
userId: 'ae149220-2883-11e7-bbf9-1fb134f2b4ad',
email: 'email2@hotmail.com',
name: 'james',
roles: 'plumber'
}]
基本上,与Object中userId匹配的键的值将添加到数组中的该对象。
有什么简单的方法我不认为这样做吗?没有ES6中的外部库?
答案 0 :(得分:1)
var data = [{
userId: 'ab4e3870-287e-11e7-b5a1-abb6183e9866',
email: 'email1@hotmail.com'
},{
userId: 'ae149220-2883-11e7-bbf9-1fb134f2b4ad',
email: 'email2@hotmail.com'
}]
var d = {
'ab4e3870-287e-11e7-b5a1-abb6183e9866': { name: 'john', roles: 'detective'},
'ae149220-2883-11e7-bbf9-1fb134f2b4ad': { name: 'james', roles: 'plumber'},
};
...
data = data.map(function(item) {
return {...item, ...d[item.userId]}
});
data = data.map(function(item) {
item.name = d[item.userId].name;
item.roles = d[item.userId].roles;
return item;
});