gpt4 book ai didi

javascript - 基于另一个对象递归更新特定键的嵌套对象值

转载 作者:行者123 更新时间:2023-12-05 08:37:18 24 4
gpt4 key购买 nike

*** 更新对象结构 ***

我想根据 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);

关于javascript - 基于另一个对象递归更新特定键的嵌套对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65847834/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com