合并两个对象并重命名相同的属性

时间:2016-08-23 06:18:25

标签: javascript jquery lodash

我有两个包含一些类似属性的对象。我想在一个对象中合并这两个对象,并且还想从两个对象重命名相似的属性。

var selectedEntity = {"UsageS":"123","DateS":"2016","IsEstimeated":"True"};
var ComapareEntity = {"UsageC":"124","DateC":"2015","IsEstimeated":"False"}

Result = {"UsageS":"123","DateS":"2016","IsEstimeatedS":"True","UsageC":"124","DateC":"2015","IsEstimeatedC":"False"};

请使用lodash建议一些解决方案。

1 个答案:

答案 0 :(得分:1)

尝试将这两个对象放在json数组中,以便索引可用于命名重复键

   var selectedEntity = {
  "UsageS": "123",
  "DateS": "2016",
  "IsEstimeated": "True"
};
var ComapareEntity = {
  "UsageC": "124",
  "DateC": "2015",
  "IsEstimeated": "False"
}

var toLoopArray = [selectedEntity, ComapareEntity]

var resultantObject = {};
toLoopArray.forEach(function(item, index) {

  for (var keys in item) {
    if (!(resultantObject.hasOwnProperty(keys))) {
      resultantObject[keys] = item[keys]
    } else {
      resultantObject[keys + index] = item[keys]
    }
  }
})
console.log(resultantObject)

JSFIDDLE