动态设置嵌套对象的属性

时间:2013-09-21 19:50:27

标签: javascript ecmascript-5

我有一个对象可以是任意数量的级别,并且可以具有任何现有属性。 例如:

var obj = {
    db: {
        mongodb: {
            host: 'localhost'
        }
    }
};

在那我想设置(或覆盖)属性如下:

set('db.mongodb.user', 'root');
// or:
set('foo.bar', 'baz');

属性字符串可以有任何深度,值可以是任何类型/东西 如果属性键已经存在,则不需要合并作为值的对象和数组。

上一个示例将生成以下对象:

var obj = {
    db: {
        mongodb: {
            host: 'localhost',
            user: 'root'
        }
    },
    foo: {
        bar: baz
    }
};

我怎样才能实现这样的功能?

21 个答案:

答案 0 :(得分:67)

此函数使用您指定的参数,应添加/更新obj容器中的数据。请注意,您需要跟踪obj模式中的哪些元素是容器,哪些是值(字符串,整数等),否则您将开始抛出异常。

obj = {};  // global object

function set(path, value) {
    var schema = obj;  // a moving reference to internal objects within obj
    var pList = path.split('.');
    var len = pList.length;
    for(var i = 0; i < len-1; i++) {
        var elem = pList[i];
        if( !schema[elem] ) schema[elem] = {}
        schema = schema[elem];
    }

    schema[pList[len-1]] = value;
}

set('mongo.db.user', 'root');

答案 1 :(得分:38)

Lodash采用_.set()方法。

for k = 1:5
    totalBinary = totalBinary | binaryImage;
    subplot(1,2,2); imshow(totalBinary); drawnow

    subplot(1,2,1); %imshow(tophatImage) % <-- Remove this
    hFH = imfreehand();
    binaryImage = createMask(hFH);
end

答案 2 :(得分:9)

有点晚了,但这里有一个非库,更简单的答案:

/**
 * Dynamically sets a deeply nested value in an object.
 * Optionally "bores" a path to it if its undefined.
 * @function
 * @param {!object} obj  - The object which contains the value you want to change/set.
 * @param {!array} path  - The array representation of path to the value you want to change/set.
 * @param {!mixed} value - The value you want to set it to.
 * @param {boolean} setrecursively - If true, will set value of non-existing path as well.
 */
function setDeep(obj, path, value, setrecursively = false) {

    let level = 0;

    path.reduce((a, b)=>{
        level++;

        if (setrecursively && typeof a[b] === "undefined" && level !== path.length){
            a[b] = {};
            return a[b];
        }

        if (level === path.length){
            a[b] = value;
            return value;
        } else {
            return a[b];
        }
    }, obj);
}

我所做的这个功能可以完全满足您的需求,而且可以做多一点。

假设我们想要更改深度嵌套在此对象中的目标值:

let myObj = {
    level1: {
        level2: {
           target: 1
       }
    }
}

所以我们会这样调用我们的函数:

setDeep(myObj, ["level1", "level2", "target1"], 3);

将导致:

myObj = {         1级: {             level2:{                目标:3            }         }     }

将set recursively flag设置为true将设置对象(如果它们不存在)。

setDeep(myObj, ["new", "path", "target"], 3);

将导致:

obj = myObj = {
    new: {
         path: {
             target: 3
         }
    },
    level1: {
        level2: {
           target: 3
       }
    }
}

答案 3 :(得分:6)

Lodash有一个名为update的方法,可以完全满足您的需求。

此方法接收以下参数:

  1. 要更新的对象
  2. 要更新的属性的路径(属性可以深层嵌套)
  3. 返回要更新的值的函数(给定原始值作为参数)
  4. 在您的示例中,它看起来像这样:

    _.update(obj, 'db.mongodb.user', function(originalValue) {
      return 'root'
    })
    

答案 4 :(得分:6)

受@ bpmason1的回答启发:

function leaf(obj, path, value) {
  const pList = path.split('.');
  const key = pList.pop();
  const pointer = pList.reduce((accumulator, currentValue) => {
    if (accumulator[currentValue] === undefined) accumulator[currentValue] = {};
    return accumulator[currentValue];
  }, obj);
  pointer[key] = value;
  return obj;
}

示例:

const obj = {
  boats: {
    m1: 'lady blue'
  }
};
leaf(obj, 'boats.m1', 'lady blue II');
leaf(obj, 'boats.m2', 'lady bird');
console.log(obj); // { boats: { m1: 'lady blue II', m2: 'lady bird' } }

答案 5 :(得分:2)

我们可以使用递归函数:

/**
 * Sets a value of nested key string descriptor inside a Object.
 * It changes the passed object.
 * Ex:
 *    let obj = {a: {b:{c:'initial'}}}
 *    setNestedKey(obj, ['a', 'b', 'c'], 'changed-value')
 *    assert(obj === {a: {b:{c:'changed-value'}}})
 *
 * @param {[Object]} obj   Object to set the nested key
 * @param {[Array]} path  An array to describe the path(Ex: ['a', 'b', 'c'])
 * @param {[Object]} value Any value
 */
export const setNestedKey = (obj, path, value) => {
  if (path.length === 1) {
    obj[path] = value
    return
  }
  return setNestedKey(obj[path[0]], path.slice(1), value)
}

这更简单!

答案 6 :(得分:2)

使用计算属性名称 Rest参数,ES6也有很酷的方法。

const obj = {
  levelOne: {
    levelTwo: {
      levelThree: "Set this one!"
    }
  }
}

const updatedObj = {
  ...obj,
  levelOne: {
    ...obj.levelOne,
    levelTwo: {
      ...obj.levelOne.levelTwo,
      levelThree: "I am now updated!"
    }
  }
}

如果levelThree是动态属性,即设置levelTwo中的任何属性,则可以使用[propertyName]: "I am now updated!" propertyName保存levelTwo中的属性名称1}}。

答案 7 :(得分:2)

我只是使用ES6 +递归编写一个小函数来实现目标。

DESC

我在更新状态的反应中使用了很多,它对我来说效果很好。

答案 8 :(得分:1)

如果您只需要更改更深层次的嵌套对象,那么另一种方法可能是引用该对象。由于JS对象由其引用处理,因此您可以创建对具有字符串键访问权限的对象的引用。

示例:

// The object we want to modify:
var obj = {
    db: {
        mongodb: {
            host: 'localhost',
            user: 'root'
        }
    },
    foo: {
        bar: baz
    }
};

var key1 = 'mongodb';
var key2 = 'host';

var myRef = obj.db[key1]; //this creates a reference to obj.db['mongodb']

myRef[key2] = 'my new string';

// The object now looks like:
var obj = {
    db: {
        mongodb: {
            host: 'my new string',
            user: 'root'
        }
    },
    foo: {
        bar: baz
    }
};

答案 9 :(得分:1)

我想出了自己的解决方案,它使用了纯es6和不会改变原始对象的递归。

const setNestedProp = (obj = {}, [first, ...rest] , value) => ({
  ...obj,
  [first]: rest.length
    ? setNestedProp(obj[first], rest, value)
    : value
});

const result = setNestedProp({}, ["first", "second", "a"], 
"foo");
const result2 = setNestedProp(result, ["first", "second", "b"], "bar");

console.log(result);
console.log(result2);

答案 10 :(得分:1)

我创建了gist,用于根据正确答案通过字符串设置和获取obj值。您可以下载它或将其作为npm / yarn软件包使用。

// yarn add gist:5ceba1081bbf0162b98860b34a511a92
// npm install gist:5ceba1081bbf0162b98860b34a511a92
export const DeepObject = {
  set: setDeep,
  get: getDeep
};

// https://stackoverflow.com/a/6491621
function getDeep(obj: Object, path: string) {
  path = path.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
  path = path.replace(/^\./, '');           // strip a leading dot
  const a = path.split('.');
  for (let i = 0, l = a.length; i < l; ++i) {
    const n = a[i];
    if (n in obj) {
      obj = obj[n];
    } else {
      return;
    }
  }

  return obj;
}

// https://stackoverflow.com/a/18937118
function setDeep(obj: Object, path: string, value: any) {
  let schema = obj;  // a moving reference to internal objects within obj
  const pList = path.split('.');
  const len = pList.length;
  for (let i = 0; i < len - 1; i++) {
    const elem = pList[i];
    if (!schema[elem]) {
      schema[elem] = {};
    }
    schema = schema[elem];
  }

  schema[pList[len - 1]] = value;
}

// Usage
// import {DeepObject} from 'somePath'
//
// const obj = {
//   a: 4,
//   b: {
//     c: {
//       d: 2
//     }
//   }
// };
//
// DeepObject.set(obj, 'b.c.d', 10); // sets obj.b.c.d to 10
// console.log(DeepObject.get(obj, 'b.c.d')); // returns 10

答案 11 :(得分:1)

另一种方法是使用递归来挖掘对象:

(function(root){

  function NestedSetterAndGetter(){
    function setValueByArray(obj, parts, value){

      if(!parts){
        throw 'No parts array passed in';
      }

      if(parts.length === 0){
        throw 'parts should never have a length of 0';
      }

      if(parts.length === 1){
        obj[parts[0]] = value;
      } else {
        var next = parts.shift();

        if(!obj[next]){
          obj[next] = {};
        }
        setValueByArray(obj[next], parts, value);
      }
    }

    function getValueByArray(obj, parts, value){

      if(!parts) {
        return null;
      }

      if(parts.length === 1){
        return obj[parts[0]];
      } else {
        var next = parts.shift();

        if(!obj[next]){
          return null;
        }
        return getValueByArray(obj[next], parts, value);
      }
    }

    this.set = function(obj, path, value) {
      setValueByArray(obj, path.split('.'), value);
    };

    this.get = function(obj, path){
      return getValueByArray(obj, path.split('.'));
    };

  }
  root.NestedSetterAndGetter = NestedSetterAndGetter;

})(this);

var setter = new this.NestedSetterAndGetter();

var o = {};
setter.set(o, 'a.b.c', 'apple');
console.log(o); //=> { a: { b: { c: 'apple'}}}

var z = { a: { b: { c: { d: 'test' } } } };
setter.set(z, 'a.b.c', {dd: 'zzz'}); 

console.log(JSON.stringify(z)); //=> {"a":{"b":{"c":{"dd":"zzz"}}}}
console.log(JSON.stringify(setter.get(z, 'a.b.c'))); //=> {"dd":"zzz"}
console.log(JSON.stringify(setter.get(z, 'a.b'))); //=> {"c":{"dd":"zzz"}}

答案 12 :(得分:0)

如果您想要一个需要先验属性存在的函数,则可以使用类似的方法,它还会返回一个标志,说明它是否设法找到并设置了嵌套属性。

function set(obj, path, value) {
    var parts = (path || '').split('.');
    // using 'every' so we can return a flag stating whether we managed to set the value.
    return parts.every((p, i) => {
        if (!obj) return false; // cancel early as we havent found a nested prop.
        if (i === parts.length - 1){ // we're at the final part of the path.
            obj[parts[i]] = value;          
        }else{
            obj = obj[parts[i]]; // overwrite the functions reference of the object with the nested one.            
        }   
        return true;        
    });
}

答案 13 :(得分:0)

JQuery具有扩展方法:

https://api.jquery.com/jquery.extend/

只需将覆盖作为对象传递,它将合并两者。

答案 14 :(得分:0)

我需要实现相同的目的,但是在Node.js中... 因此,我找到了一个不错的模块:https://www.npmjs.com/package/nested-property

示例:

var mod = require("nested-property");
var obj = {
  a: {
    b: {
      c: {
        d: 5
      }
    }
  }
};
console.log(mod.get(obj, "a.b.c.d"));
mod.set(obj, "a.b.c.d", 6);
console.log(mod.get(obj, "a.b.c.d"));

答案 15 :(得分:0)

受ClojureScript的assoc-inhttps://github.com/clojure/clojurescript/blob/master/src/main/cljs/cljs/core.cljs#L5280)启发,使用递归:

/**
 * Associate value (v) in object/array (m) at key/index (k).
 * If m is falsy, use new object.
 * Returns the updated object/array.
 */
function assoc(m, k, v) {
    m = (m || {});
    m[k] = v;
    return m;
}

/**
 * Associate value (v) in nested object/array (m) using sequence of keys (ks)
 * to identify the path to the nested key/index.
 * If one of the values in the nested object/array doesn't exist, it adds
 * a new object.
 */
function assoc_in(m={}, [k, ...ks], v) {
    return ks.length ? assoc(m, k, assoc_in(m[k], ks, v)) : assoc(m, k, v);
}

/**
 * Associate value (v) in nested object/array (m) using key string notation (s)
 * (e.g. "k1.k2").
 */
function set(m, s, v) {
    ks = s.split(".");
    return assoc_in(m, ks, v);
}

注意:

通过提供的实现,

assoc_in({"a": 1}, ["a", "b"], 2) 

返回

{"a": 1}

在这种情况下,我希望它抛出一个错误。如果需要,可以在assoc中添加检查以确认m是对象还是数组,否则抛出错误。

答案 16 :(得分:0)

我试图简短地编写此 set方法,它可能会对某人有所帮助!

function set(obj, key, value) {
 let keys = key.split('.');
 if(keys.length<2){ obj[key] = value; return obj; }

 let lastKey = keys.pop();

 let fun = `obj.${keys.join('.')} = {${lastKey}: '${value}'};`;
 return new Function(fun)();
}

var obj = {
"hello": {
    "world": "test"
}
};

set(obj, "hello.world", 'test updated'); 
console.log(obj);

set(obj, "hello.world.again", 'hello again'); 
console.log(obj);

set(obj, "hello.world.again.onece_again", 'hello once again');
console.log(obj);

答案 17 :(得分:0)

const set = (o, path, value) => {
    const props = path.split('.');
    const prop = props.shift()
    if (props.length === 0) {
        o[prop] = value
    } else {
        o[prop] = o[prop] ?? {}
        set(o[prop], props.join('.'), value)
    }
}

答案 18 :(得分:0)

晚会 - 这是一个普通的js函数,它接受一个路径作为参数并返回修改后的对象/json

let orig_json = {
  string: "Hi",
  number: 0,
  boolean: false,
  object: {
    subString: "Hello",
    subNumber: 1,
    subBoolean: true,
    subObject: {
      subSubString: "Hello World"
    },
    subArray: ["-1", "-2", "-3"]
  },
  array: ["1", "2", "3"]
}

function changeValue(obj_path, value, json) {
  let keys = obj_path.split(".")
  let obj = { ...json },
    tmpobj = {},
    prevobj = {}
  for (let x = keys.length - 1; x >= 0; x--) {
    if (x == 0) {
      obj[keys[0]] = tmpobj
    } else {
      let toeval = 'json.' + keys.slice(0, x).join('.');
      prevobj = { ...tmpobj
      }
      tmpobj = eval(toeval);
      if (x == keys.length - 1) tmpobj[keys[x]] = value
      else {
        tmpobj[keys[x]] = prevobj
      }
    }
  }
  return obj
}

let newjson = changeValue("object.subObject.subSubString", "Goodbye world", orig_json);
console.log(newjson)

答案 19 :(得分:0)

另一种添加或覆盖属性的解决方案:

function propertySetter(property, value) {
  const sampleObject = {
    string: "Hi",
    number: 0,
    boolean: false,
    object: {
      subString: "Hello",
      subNumber: 1,
      subBoolean: true,
      subObject: {
        subSubString: "Hello World",
      },
      subArray: ["-1", "-2", "-3"],
    },
    array: ["1", "2", "3"],
  };

  const keys = property.split(".");
  const propertyName = keys.pop();
  let propertyParent = sampleObject;
  while (keys.length > 0) {
    const key = keys.shift();
    if (!(key in propertyParent)) {
      propertyParent[key] = {};
    }
    propertyParent = propertyParent[key];
  }
  propertyParent[propertyName] = value;
  return sampleObject;
}

console.log(propertySetter("object.subObject.anotherSubString", "Hello you"));

console.log(propertySetter("object.subObject.subSubString", "Hello Earth"));

console.log(propertySetter("object.subObject.nextSubString.subSubSubString", "Helloooo"));

答案 20 :(得分:0)

扩展 @bpmason1 提供的已接受答案,以支持字符串路径中的数组,例如字符串路径可以是 'db.mongodb.users[0].name''db.mongodb.users[1].name'

它会设置属性值,如果不存在,将被创建。

var obj = {};

function set(path, value) {
  var schema = obj;
  var keysList = path.split('.');
  var len = keysList.length;
  for (var i = 0; i < len - 1; i++) {
    var key = keysList[i];
    // checking if key represents an array element e.g. users[0]
    if (key.includes('[')) {
      //getting propertyName 'users' form key 'users[0]'
      var propertyName = key.substr(0, key.length - key.substr(key.indexOf("["), key.length - key.indexOf("[")).length);
      if (!schema[propertyName]) {
        schema[propertyName] = [];
      }
      // schema['users'][getting index 0 from 'users[0]']
      if (!schema[propertyName][parseInt(key.substr(key.indexOf("[") + 1, key.indexOf("]") - key.indexOf("[") - 1))]) {
        // if it doesn't exist create and initialise it
        schema = schema[propertyName][parseInt(key.substr(key.indexOf("[") + 1, key.indexOf("]") - key.indexOf("[") - 1))] = {};
      } else {
        schema = schema[propertyName][parseInt(key.substr(key.indexOf("[") + 1, key.indexOf("]") - key.indexOf("[") - 1))];
      }
      continue;
    }
    if (!schema[key]) {
      schema[key] = {};
    }
    schema = schema[key];
  } //loop ends
  // if last key is array element
  if (keysList[len - 1].includes('[')) {
    //getting propertyName 'users' form key 'users[0]'
    var propertyName = keysList[len - 1].substr(0, keysList[len - 1].length - keysList[len - 1].substr(keysList[len - 1].indexOf("["), keysList[len - 1].length - keysList[len - 1].indexOf("[")).length);
    if (!schema[propertyName]) {
      schema[propertyName] = [];
    }
    // schema[users][0] = value;
    schema[propertyName][parseInt(keysList[len - 1].substr(keysList[len - 1].indexOf("[") + 1, keysList[len - 1].indexOf("]") - keysList[len - 1].indexOf("[") - 1))] = value;
  } else {
    schema[keysList[len - 1]] = value;
  }
}

// will create if not exist
set("mongo.db.users[0].name.firstname", "hii0");
set("mongo.db.users[1].name.firstname", "hii1");
set("mongo.db.users[2].name", {
  "firstname": "hii2"
});
set("mongo.db.other", "xx");
console.log(obj);

// will set if exist
set("mongo.db.other", "yy");
console.log(obj);