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

Dra*_*osB 2 javascript oop recursion

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

我想从 updateObject 中存在的属性中递归更新 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
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

我已经添加了一个 Codepen 链接来解决以下问题:我仍然需要做的是找到要更新的正确属性(例如“age”属性对于更多对象来说很常见)。

TL;DR: mainObject 中的猫龄应为 8

https://codepen.io/Dragosb/pen/bGwypKz?editors=0012

Gab*_*oli 7

您可以同步遍历

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);
Run Code Online (Sandbox Code Playgroud)