比较两个数组并添加或替换内容?

时间:2019-07-12 07:23:00

标签: javascript arrays filter

我有一个对象 A B 。对象 B 将与 A 进行比较。 B 中的新内容应添加到 A 中。如果 A B 处的键相同,则 B 的内容将替换为 A

简而言之: A 是我的默认对象,对象 B 应该覆盖内容或再次将其添加到对象 A

正确的方法是搜索重复的条目并将其删除。然后将对象B完全添加到A中。这是正确的吗?我该怎么办?

对象A如下:

{
  "slidesPerView": 3,
  "direction": "vertical",
  "roundLengths": true,
  "keyboard": {
    "enabled": true,
    "onlyInViewport": true
  },
  "breakpoints": {
    576: {
      "direction": "horizontal",
      "slidesPerView": "auto"
    }
  }
}

对象B如下:

{
  "slidesPerView": "auto",
  "direction": "horizontal",
  "roundLengths": false,
  "breakpoints": {
    576: {
      "direction": "vertical",
      "slidesPerView": 5
    }
  }
}

结果将是以下内容:

{
  "slidesPerView": "auto",
  "direction": "horizontal",
  "roundLengths": false,
  "keyboard": {
    "enabled": true,
    "onlyInViewport": true
  },
  "breakpoints": {
    576: {
      "direction": "vertical",
      "slidesPerView": 5
    }
  }
}

1 个答案:

答案 0 :(得分:1)

实际上,您不需要搜索重复的密钥。您可以直接遍历objectB,并将其每个密钥添加到objectA

for (var key in objectB) {
  objectA[key] = objectB[key]; // If key exists in objectA, it will be overwritten with the value from objectB. If it doesn't, it will be created (with the value from objectB)
}

console.log(JSON.stringify(objectA)); // This should output the result you were looking for