使用lodash映射具有匹配属性的2个不同对象

时间:2018-01-15 08:43:03

标签: angularjs node.js lodash

我基本上对lodash不熟悉,但我知道很多这样的魔法可以在lodash的帮助下轻松完成。所以我试图在这里使用lodash映射2个不同的对象。

这是我的对象。

var obj_one = [{
  "username": "bob",
   "adminType": "facebook",
},
{
  "username": "tom",
  "adminType": "twitter"
},
{
  "username": "bob",
  "adminType": "twitter"
}];

var obj2 = {
  "bob": {
    "full_name": "Bob Something",
    "department": "Social Site",
  },
  "tom": {
    "full_name": "Tom Something",
    "department": "Networking Site",
  },
  "harry": {
    "full_name": "Harry something",
    "department": "Principal Engineering"
  }
}

在我的结果输出中,我想从obj2将department属性追加到obj1。

obj_result = [{
  "username": "bob",
   "adminType": "facebook",
   "department": "Social Site"
},
{
  "username": "tom",
  "adminType": "twitter",
   "department": "Networking Site"
},
{
  "username": "bob",
   "adminType": "twitter",
   "department": "Social Site"
}];

我想我可以通过遍历其中一个对象并以某种方式处理数据来实现这一点。但是,如果可以通过lodash完成,这可能真的非常有用。

1 个答案:

答案 0 :(得分:2)

使用vanilla JS(或lodash的等价物),您可以使用Array#map迭代数组,并使用Object#assign创建包含department属性的新对象:

var arr = [{"username":"bob","adminType":"facebook"},{"username":"tom","adminType":"twitter"},{"username":"bob","adminType":"twitter"}];

var obj = {"bob":{"full_name":"Bob Something","department":"Social Site"},"tom":{"full_name":"Tom Something","department":"Networking Site"},"harry":{"full_name":"Harry something","department":"Principal Engineering"}};

var result = arr.map(function(o) {
  return Object.assign({}, o, { department: obj[o.username].department });
});

console.log(result);