使用 Javascript 的嵌套对象分配

Nested Object Assign using Javascript

    var obj1 = {
      a: "imgood",
      b: {
        a1: {
          a2: "i shouldnt be here",
          b2: "imgood"
        },
        b1: "imgood"
      }
    };
    
    var obj2 = {
      b: {
        a1: {
          a2: "imgood"
        }
      }
    };
    console.log(Object.assign(obj1,obj2));

我希望更换 a2 但不丢失其他属性。

尽可能以最简单、最短和最快的方式

obj1.b.a1obj2.b.a1传递给Object.assign()

var obj1 = {
      a: "imgood",
      b: {
        a1: {
          a2: "i shouldnt be here",
          b2: "imgood"
        },
        b1: "imgood"
      }
    };
    
    var obj2 = {
      b: {
        a1: {
          a2: "imgood"
        }
      }
    };


Object.assign(obj1.b.a1, obj2.b.a1);

console.log(obj1);

您可以使用迭代和递归方法来分配值。

此提案迭代源对象并在必要时创建新的目标属性,如果未找到嵌套对象则分配值。

function update(target, source) {
    Object.keys(source).forEach(function(key) {
        if (source[key] && typeof source[key] === 'object') {
            return update(target[key] = target[key] || (Array.isArray(source[key]) ? [] : {}), source[key]);
        }
        target[key] = source[key];
    });
}

var obj1 = { a: "imgood", b: { a1: { a2: "i shouldnt be here", b2: "imgood" }, b1: "imgood" } },
    obj2 = { b: { a1: { a2: "imgood" } } };

update(obj1, obj2);
console.log(obj1);
.as-console-wrapper { max-height: 100% !important; top: 0; }

你的对象具有相似的结构,所以你可以通过一个非常简单的函数来实现:

var obj1 = {
  a: "imgood",
  b: {
    a1: {
      a2: "i shouldnt be here",
      b2: "imgood"
    },
    b1: "imgood"
  }
};
    
var obj2 = {
  b: {
    a1: {
      a2: "imgood"
    }
  }
};

function changeA2 (obj) {
  obj['b']['a1']['a2'] = 'CHANGED';
  return obj;
}

console.log("new obj1: ", changeA2(obj1));
console.log("new obj2: ", changeA2(obj2));

这是一个在递归函数中使用 for 循环的解决方案:

function recursiveAssign(a, b) {
    if (Object(b) !== b) return b;
    if (Object(a) !== a) a = {};
    for (let key in b) {
        a[key] = recursiveAssign(a[key], b[key]);
    }
    return a;
}

var obj1 = {
  a: "imgood",
  b: {
    a1: {
      a2: "i shouldnt be here",
      b2: "imgood"
    },
    b1: "imgood"
  }
};

var obj2 = {
  b: {
    a1: {
      a2: "imgood"
    }
  }
};

console.log(recursiveAssign(obj1, obj2));
.as-console-wrapper { max-height: 100% !important; top: 0; }

或以功能方式:

function recursiveAssign(a, b) {
    return Object(b) !== b ? b 
        : Object.keys(b).reduce ( (a, key) =>
            Object.assign(a, { [key]: recursiveAssign(a[key], b[key]) })
          , Object(a) === a ? a : {} );
}

var obj1 = {
  a: "imgood",
  b: {
    a1: {
      a2: "i shouldnt be here",
      b2: "imgood"
    },
    b1: "imgood"
  }
};

var obj2 = {
  b: {
    a1: {
      a2: "imgood"
    }
  }
};

console.log(recursiveAssign(obj1, obj2));
.as-console-wrapper { max-height: 100% !important; top: 0; }