Javascript - Lodash / Underscore比较两个对象并根据其键更改值

时间:2016-03-14 14:55:35

标签: javascript arrays underscore.js lodash

有一个小问题

我需要比较两个对象,并根据这些对象中的相同键将值从第二个对象传递给原始对象。

原始对象

{
   content: "Old Value",
   height: 200,
   id: "15a2d286-d123-1cf0-4e40-b043b055a49f",
   type: "location",
   units: "some unit value",
   width: 200,
}

第二个对象

{
   units: "some unit value", 
   content: "New Value"
}

无需检查密钥

输出将是那样的

{
   content: "New Value", // changed value
   height: 200,
   id: "15a2d286-d123-1cf0-4e40-b043b055a49f",
   type: "location",
   units: "some unit value", // changed value
   width: 200,
}

Lodash或Underscore是否有任何优雅的解决方案?

1 个答案:

答案 0 :(得分:0)

这将解决问题(使用lodash)

var source = {
  content: "Old Value",
  height: 200,
  id: "15a2d286-d123-1cf0-4e40-b043b055a49f",
  type: "location",
  units: "some unit value",
  width: 200,
},
source2 = {
  units: "some unit value", 
  content: "New Value"
}
_.assignIn(source , source2 );