对象操作javascript,将对象的值添加到对象数组中

时间:2017-04-24 01:56:24

标签: javascript arrays concatenation javascript-objects

一个例子可以说明一切:

对象数组:

[{ 
    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中的外部库?

1 个答案:

答案 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'}, 
};

使用ES6传播运算符...

data = data.map(function(item) {
  return {...item, ...d[item.userId]}
});

ES5:手动添加属性

data = data.map(function(item) {
  item.name = d[item.userId].name;
  item.roles = d[item.userId].roles;
  return item;
});