如何根据对象在对象中的位置修改对象 属性

How to modify an object property given its location within the object

给定一个对象 obj,我可以使用 obj.a.b.c = "new value" 之类的东西修改它的属性。但是,我希望能够以编程方式使用数组形式的 属性 位置来执行此操作。我怎样才能制作一个看起来像这样的函数:

modifyProperty(obj, ["a", "b", "c"], "new value");

相当于

obj.a.b.c = "new value";

?

你可以这样做:

function modifyProperty(obj, props, val) {
    var propName = props.pop();
    var o = props.reduce(function(obj, p) {
        return obj[p];
    }, obj);
    o[propName] = val;
}

var obj = {
   a: {b: {c: "old value"}}
}

modifyProperty(obj, ["a", "b", "c"], "new value");

console.log(obj);

为了动态设置对象值,我有一个名为 Object.prototype.setNestedValue() 的代码,这将采用指定数组属性的项目数组,最后一个是值。如

Object.prototype.setNestedValue = function(...a) {
  a.length > 2 ? typeof this[a[0]] === "object" && this[a[0]] !== null ? this[a[0]].setNestedValue(...a.slice(1))
                                                                       : (this[a[0]] = typeof a[1] === "string" ? {} : new Array(a[1]),
                                                                         this[a[0]].setNestedValue(...a.slice(1)))
               : this[a[0]] = a[1];
  return this;
};

var obj = {}.setNestedValue("a","b","c",100);
console.log(JSON.stringify(obj,null,2));

如果您使用整数而不是字符串参数,您会得到一个数组,例如

Object.prototype.setNestedValue = function(...a) {
      a.length > 2 ? typeof this[a[0]] === "object" && this[a[0]] !== null ? this[a[0]].setNestedValue(...a.slice(1))
                                                                           : (this[a[0]] = typeof a[1] === "string" ? {} : new Array(a[1]),
                                                                             this[a[0]].setNestedValue(...a.slice(1)))
                   : this[a[0]] = a[1];
      return this;
    };

    var obj = {}.setNestedValue("a",2 ,3,100);
    console.log(JSON.stringify(obj,null,2));

您可以使用 Array#reduce,如果没有对象可用,则使用默认对象。

function modifyProperty(object, path, value) {
    var last = path.pop();
    path.reduce(function (r, a) {
        if (!(a in r)) {
            r[a] = {};
        }
        return r[a];
    }, object)[last] = value;
}

var object = {};
modifyProperty(object, ["a", "b", "c"], "new value");
console.log(object);