使用更改的值访问Javascript对象

时间:2016-07-22 16:41:09

标签: javascript json

如果我有JSON,例如:

   {
   "test1":{
      "test11":"someting",
      "test12":"something else"
   },
   "test2":{
      "test21":"asdasd",
      "test22":"qwasd"
   }
}

我想访问和修改一些数据,但我不知道哪一个。 我会有一系列像这样的键:

["test2","test22"]和值:"change to this"

我想将myjson.test2.test22数据更改为"change to this"

有一些简单而优雅的方法吗?

请注意,我不知道数组的内容是什么,因此我无法使用myjson.test2.test22访问方法。

6 个答案:

答案 0 :(得分:3)

试试这个



    function setDeep(obj, props, value) {
      var cur = obj,
        prop;

      while ((prop = props.shift()) && props.length) {
        cur = cur[prop]
      }

      cur[prop] = value
      return obj;
    }

    var obj = {
      "test1": {
        "test11": "someting",
        "test12": "something else"
      },
      "test2": {
        "test21": "asdasd",
        "test22": "qwasd"
      }
    }

    setDeep(obj, ['test1', 'test12'], 'new value');

    console.log(obj)




答案 1 :(得分:1)

以下是递归函数,遍历对象的键,直到找到匹配的键(数组中的最后一个键),然后更改它的值并返回更改的对象。基本情况是键数组为空时。如果找不到密钥,则返回false

给出一个名为obj的对象

var obj =    {
   "test1":{
      "test11":"someting",
      "test12":"something else"
       },
       "test2":{
          "test21":"asdasd",
          "test22":"qwasd"
       }



 function changeAkey(object, arrayOfKeys, value){
   if(arrayOfKeys.length == 0)
      return value;
   else{
      if(!object[arrayOfKeys[0]])
         return false;
      else
         object[arrayOfKeys[0]] = changeAkey(object[arrayOfKeys[0]], arrayOfKeys.slice(1), value);
         return object;
   }
}

所以changeAkey(obj, ["test2", "test22"], value)会完成这项工作

答案 2 :(得分:1)

您可以使用Array#reduce并走这条路。然后使用最后一个键将值赋给对象。

var object = { "test1": { "test11": "someting", "test12": "something else" }, "test2": { "test21": "asdasd", "test22": "qwasd" } },
    path = ["test2", "test22"],
    lastKey = path.pop();

path.reduce(function (o, k) {
    return o[k];
}, object)[lastKey] = 'change to this';

console.log(object);

对于未知属性,我建议进行检查,然后使用默认对象。

var object = { "test1": { "test11": "someting", "test12": "something else" }, "test2": { "test21": "asdasd", "test22": "qwasd" } },
    path = ["test2", "test22", "42"],
    lastKey = path.pop();

path.reduce(function (o, k) {
    (o[k] !== null && typeof o[k] === 'object') || (o[k] = {});
    return o[k];
}, object)[lastKey] = 'change to this';

console.log(object);

答案 3 :(得分:0)

我首先检查属性是否存在以及是否确实更改了数据。这样它就不会抛出非特定的错误。

var keys = ["key1", "key2"];
var myObj = {
  "random1": {
    "random2": "someting",
    "random3": "something else"
  },
  "key1": {
    "random4": "asdasd",
    "key2": "qwasd"
  };
}

var hasKeys = myObj[keys[0]][keys[1]] || null;
if(hasKeys) {
  myObj[keys[0]][keys[1]] = "some data";
} else {
  console.log('property not found');
}

答案 4 :(得分:0)

我建议序列化你的对象并使用String replace()。它适用于任何深度和简单的代码。

var objStr = JSON.stringify(obj);

changes.forEach(function(item){
   objStr = objStr.replace(item, to);   
})

obj = JSON.parse(objStr);



var obj = {
   "test1":{
      "test11":"someting",
      "test12":"something else"
   },
   "test2":{
      "test21":"asdasd",
      "test22":"qwasd"
   }
}


var changes = ["test11", "test21"];
var to = 'change to this';

var objStr = JSON.stringify(obj);

changes.forEach(function(item){
   objStr = objStr.replace(item, to);   
})

obj = JSON.parse(objStr);
console.log(obj)




答案 5 :(得分:0)

var obj =  {
	"test1":{
		"test11":"someting",
		"test12":"something else"
	},
	"test2":{
		"test21":"asdasd",
		"test22":"qwasd"
	}
};

var keys = ["test2","test22"];

function update_obj(obj, keys, value) {

	for (var i = 0; i < keys.length - 1; i++) {
		obj = obj[keys[i]];
	}
	obj[keys[keys.length - 1]] = value;
}
update_obj(obj, keys, "hi");

console.log(obj);