Javascript 比较两个数组并添加或替换内容?
我有一个对象A和B。对象B将与A进行比较。B中的新内容应添加到A。如果A和B的键相同,则B的内容将在A中替换 简言之: A是我的默认对象,对象B应覆盖内容或再次将其添加到对象A 正确的方法是搜索重复条目并删除它们。然后将对象B完全添加到A中,对吗?我该怎么做 对象A如下所示:Javascript 比较两个数组并添加或替换内容?,javascript,arrays,filter,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,
{
"slidesPerView": 3,
"direction": "vertical",
"roundLengths": true,
"keyboard": {
"enabled": true,
"onlyInViewport": true
},
"breakpoints": {
576: {
"direction": "horizontal",
"slidesPerView": "auto"
}
}
}
{
"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
}
}
}
对象B如下所示:
{
"slidesPerView": 3,
"direction": "vertical",
"roundLengths": true,
"keyboard": {
"enabled": true,
"onlyInViewport": true
},
"breakpoints": {
576: {
"direction": "horizontal",
"slidesPerView": "auto"
}
}
}
{
"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
}
}
}
结果如下:
{
"slidesPerView": 3,
"direction": "vertical",
"roundLengths": true,
"keyboard": {
"enabled": true,
"onlyInViewport": true
},
"breakpoints": {
576: {
"direction": "horizontal",
"slidesPerView": "auto"
}
}
}
{
"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
}
}
}
实际上,您不需要搜索重复的密钥。您可以直接迭代
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个嵌套对象。也许您可以执行递归操作。