*** 更新对象结构 ***
我想根据 updatingObject 中存在的属性递归更新 mainObject 的属性值。
let mainObject = {
age: 24,
isMarried: false,
pets: {
dog: {
name: "Juniper",
age: 3
},
cat: {
name: "Spasia",
age: 7
}
},
hobbies: {
mountainRelated: ["hiking", "snowboarding"]
}
}
let updatingObject = {
pets: {
cat: {
age: 8
}
}
}
我已经添加了指向以下问题的 Codepen 链接:我仍然需要做的是找到要更新的正确属性(例如,“age”属性对于更多对象是通用的)。
TL;DR:在 mainObject 中猫的年龄应该是 8
https://codepen.io/Dragosb/pen/bGwypKz?editors=0012
最佳答案
可以同步遍历
let mainObject = {
age: 24,
isMarried: false,
pets: {
dog: { name: "Juniper", age: 3 },
cat: { name: "Spasia", age: 7 }
},
hobbies: {
mountainRelated: ["hiking", "snowboarding"]
}
}
let updatingObject = {
pets: {
cat: {
age: 8,
name:'gabriele'
}
}
}
function updateObject(target, update){
// for each key/value pair in update object
for (const [key,value] of Object.entries(update)){
// if target has the relevant key and
// the type in target and update is the same
if (target.hasOwnProperty(key) && typeof(value) === typeof(target[key])){
// update value if string,number or boolean
if (['string','number','boolean'].includes(typeof value) || Array.isArray(value)){
target[key] = value;
} else {
// if type is object then go one level deeper
if (typeof value === 'object'){
updateObject(target[key], value)
}
}
}
}
}
updateObject(mainObject,updatingObject)
console.log(mainObject);
https://stackoverflow.com/questions/65847834/