gpt4 book ai didi

javascript - 更新嵌套的 JS 对象而不覆盖缺失的属性

转载 作者:行者123 更新时间:2023-12-04 00:13:37 25 4
gpt4 key购买 nike

EDIT: Thanks 4 all the great, diverse answers - I chose the solution that worked for me even after I realized that I needed more requirements: I also needed new properties to be added and for it to work with arrays in objects as well.


这就是我想做的:通过另一个对象更新一个对象。
以下是一些限制条件:
  • 只有新对象具有的属性应该更新(并且原始对象也有),其他属性应该保持不变,不删除
  • 嵌套对象也应该以相同的方式更新

  • 我的问题是我不知道如何轻松地为嵌套对象执行此操作,因为 typeof x === "object"例如,对于 Date 对象也返回 true。
    这是我到目前为止得到的:

    let originalObj = {
    dateCreated: new Date(2021, 1, 10),
    value: "100",
    subObj: {
    count: 55,
    val: null
    }
    };

    let updateObj = {
    dateCreated: new Date(2021, 1, 11),
    subObj: {
    val: 90
    }
    };

    let updateOrignal = (oObj, uObj) => {
    for (let prop in uObj) {
    if (uObj.hasOwnProperty(prop) &&
    oObj.hasOwnProperty(prop)) {
    oObj[prop] = uObj[prop];
    }
    }
    };

    console.log(originalObj);
    updateOrignal(originalObj, updateObj)
    console.log(originalObj);

    目前我更新的对象如下所示:
    {
    "dateCreated": "2021-02-10T23:00:00.000Z",
    "value": "100",
    "subObj": {
    "val": 90
    }
    }
    我的目标:
    {
    "dateCreated": "2021-02-10T23:00:00.000Z",
    "value": "100",
    "subObj": {
    "count": 55,
    "val": 90
    }
    }

    最佳答案

    这是您需要的解决方案(来自 https://gist.github.com/ahtcx/0cd94e62691f539160b32ecda18af3d6),实际上您可以在 google 上搜索“深度合并”或“递归合并两个 javascript 对象”
    我添加了 ES6 sintax {...obj} 以确保在合并对象之前克隆它们

    let originalObj = {
    dateCreated: new Date(2021, 1, 10),
    value: "100",
    subObj: {
    count: 55,
    val: null
    }
    };

    let updateObj = {
    dateCreated: new Date(2021, 1, 11),
    subObj: {
    val: 90
    }
    };

    const merge = (target, source) => {
    // Iterate through `source` properties and if an `Object` set property to merge of `target` and `source` properties
    for (const key of Object.keys(source)) {
    if (source[key] instanceof Object) Object.assign(source[key], merge(target[key], source[key]))
    }
    // Join `target` and modified `source`
    Object.assign(target || {}, source)
    return target
    }

    console.log(merge({ ...originalObj}, {...updateObj}));

    关于javascript - 更新嵌套的 JS 对象而不覆盖缺失的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65817636/

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