Javascript 覆盖某些对象键



所以,我有一个对象,例如

let header = {
"navbar": {
"buttons": {
0: {
"content": "home",
"color": "blue",
"href": "home"
},
1: {
"content": "shop",
"color": "red",
"href": "shop"
},
2: {
"content": "contact",
"color": "gold",
"href": "contact"
}
}
}
};

我还有第二个对象:

let header = {
"navbar": {
"buttons": {
0: {
"content": "work",
},
2: {
"color": "blue",
"href": "test"
}
}
}
};

现在我想更新第二个对象中存在的第一个对象键。所以对象看起来像这样:

let header = {
"navbar": {
"buttons": {
0: {
"content": "work",
"color": "blue",
"href": "home"
},
1: {
"content": "shop",
"color": "red",
"href": "shop"
},
2: {
"content": "contact",
"color": "blue",
"href": "test"
}
}
}
};

解决这个问题的最简单方法是什么? 提前感谢, 贾里

const header1 = {
navbar: {
buttons: {
0: {
content: "home",
color: "blue",
href: "home",
},
1: {
content: "shop",
color: "red",
href: "shop",
},
2: {
content: "contact",
color: "gold",
href: "contact",
},
},
},
};
const header2 = {
navbar: {
buttons: {
0: {
content: "work",
},
2: {
color: "blue",
href: "test",
},
},
},
};
const header = {
navbar: {
buttons: {},
},
};
// only given the keys are sequel
const header1Keys = Object.keys(header1.navbar.buttons)
const header2Keys = Object.keys(header2.navbar.buttons)
const keys = header1Keys.length > header2Keys.length ? header1Keys : header2Keys;
for (const key of keys) {
header.navbar.buttons[key] = {...header1.navbar.buttons[key], ...header2.navbar.buttons[key]}
}
console.log(header)

您可以通过不同的方式实现这一点,一种方法可能是循环每个按钮并将它们与Object.assign()合并。

下面是一个粗略的示例,对象 A 中的键将被保留并使用对象 B 中的相应键的值进行更新(合并((将添加新键的字母(:

// Initial values.
var objectA = {
0: {
a: "A0",
b: "B0",
c: "C0"
},
1: {
a: "A1",
c: "C1",
d: "D1"
},
2: {
b: "B2"
},
3: {
d: "D3",
e: "E3",
f: "F3"
},
};
// Update values.
var objectB = {
1: {
a: "A1(updated)",
b: "B1(added)",
c: "C1(updated)"
},
2: {
a: "A2(added)",
b: "B2(updated)",
c: "C2(added)"
},
3: {
a: "A3",
c: "C3",
d: "D3(updated)"
},
10: {
z: "Z10"
},
11: {
y: "Y11"
},
};
/**
* Update one object values with the values of an other object.
*/
function updateObjectValues(obj1, obj2) {
for (var key in obj1) {
// Skip key from obj2 that is not in obj1.
if (!obj2.hasOwnProperty(key)) continue;
// Update (merge) the key object from obj1 with obj2. 
obj1[key] = Object.assign(obj1[key], obj2[key]);
}
}
updateObjectValues(objectA, objectB);
console.info(objectA);

最新更新