代码之家  ›  专栏  ›  技术社区  ›  Felix

使用另一个对象的属性值对现有的(通用/任意)对象进行深度/ TS/JS深度更新

  •  0
  • Felix  · 技术社区  · 5 年前

    objA-正在更新的对象;

    两个对象中的所有属性都是可选的。我们希望这是一个泛型函数,因此没有特定的属性或属性数。

    如果在Obja中不存在属性,而在Objb中存在该属性,则该属性将被添加到Obja。 否则,objA将保留自己的属性和值(不在objB中的属性和值)。

                        /**
                         * @ngModule CommonModule
                         * @description
                         *      Deep update of an existing object with property values
                         *      of another object.
                         *      If  
                         * @param objA - the object to be updated
                         * @param objB - the object whose property values will be used
                         *                      to update 'objA'
                         */
    export function updateObject(objA: Object, objB: Object) {
    
        Object.keys(objB).forEach(key => {
                        // if a property of the:  objB 
                        // does not exist in the: objA 
                        // add it to the:  objA 
            if (objA[key] === undefined) {
                objA[key] = objB[key];
                        // if the 2 respective properties do not match - update
            } else if (objA[key] !== objB[key]) {
                        // if a property value is another object 
                        // with 2 or more properties,
                        // process recursively 
                if (Object.keys(objA[key]).length > 1) {
                    updateObject(objA[key], objB[key]);
                        // otherwise assign new value
                } else {
                    objA[key] = objB[key];
                }
            }
        });
    }
    
    0 回复  |  直到 5 年前