【问题标题】:Compare two arrays and add or replace content?比较两个数组并添加或替换内容?
【发布时间】:2019-07-12 07:23:00
【问题描述】:

我有一个对象 AB。对象 B 将与 A 进行比较。 B 的新内容应添加到 A。如果AB的key相同,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
    }
  }
}

【问题讨论】:

    标签: javascript arrays filter


    【解决方案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
    

    【讨论】:

    • 这样不行。嵌套对象被完全覆盖。如果只更改一个选项,则应保留现有选项。
    • 哦,我明白了。嵌套对象可以有多深?
    • 抱歉我的回复晚了。最多可以有 3 个嵌套对象。
    • 也许你可以做一些递归的事情。
    猜你喜欢
    • 2020-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-28
    • 1970-01-01
    • 2020-08-08
    • 2023-04-04
    相关资源
    最近更新 更多