【问题标题】:How to modify an object property given its location within the object给定对象在对象中的位置,如何修改对象属性
【发布时间】:2017-01-11 01:06:19
【问题描述】:

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

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

和等价于

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

?

【问题讨论】:

    标签: javascript object reflection pass-by-reference


    【解决方案1】:

    你可以使用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);

    【讨论】:

      【解决方案2】:

      你可以这样做:

      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);

      【讨论】:

        【解决方案3】:

        为了动态设置对象值,我有一个名为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));

        【讨论】:

        猜你喜欢
        • 2013-05-17
        • 2016-01-09
        • 2020-03-09
        • 1970-01-01
        • 1970-01-01
        • 2019-08-22
        • 2020-04-21
        相关资源
        最近更新 更多