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

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

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

相关文章:

node.js - 如何监视我的 azure 函数的变化?

visual-studio-code - 更新 VS CODE 加载工作区文件夹时出错

c - 为什么我的 C 中的 sin 计算代码返回错误的值?

c++ - 为什么C中总是有main函数?

c - sizeof 运算符在 c 中显示错误的结构大小

python - 检查列表与列表理解重叠

python - 按值属性对字典进行排序

c# - EF Core 5.0 - 更新 ASP.NET Core Web API 中的多对多实体

python - 如何将 seaborn 图保存为 svg 或 png

python - 获取不规则形状的中心