Javascript(子)通过键数组进行对象访问

时间:2016-02-09 02:32:37

标签: javascript arrays object javascript-objects

是否可以通过键数组在对象中设置变量? 例如,我有这个对象:

var obj = {'outer': {'inner': 'value'} };

并希望设置由数组键选择的值:

var keys = ['outer', 'inner'];

新价值' newValue'为了得到这个结果:

obj = {'outer': {'inner': 'newValue'} };

2 个答案:

答案 0 :(得分:3)

你可以做的是迭代键数组,确保每个键都存在并引向另一个对象,直到你到达最后一个键,用于设置新值。

function setVal(obj, keys, value) {
  var o = obj,
    len = keys.length;

  // iterate through all keys, making sure each key exists and points to an object
  for (var i = 0; i < len - 1; i++) {
    var key = keys[i];

    // check if the current key exists and is an object
    if (obj.hasOwnProperty(key) && typeof obj[key] === 'object' && obj[key]) {
      o = o[key];
    } else {
      // return false or throw an error cause the key is not an object or is missing. 
    }
  }

  // update the value at the last key
  o[keys[len - 1]] = value;
}

这是一个正在运行的例子:

&#13;
&#13;
function setVal(obj, keys, value) {
  var o = obj,
    len = keys.length;
  for (var i = 0; i < len - 1; i++) {
    var key = keys[i];
    if (obj.hasOwnProperty(key) && typeof obj[key] === 'object' && obj[key]) {
      o = o[key];
    } else {
      throw new Error('Key ' + key + ' is not an object or is missing.');
    }
  }
  o[keys[len - 1]] = value;
}

var obj = {
  'outer': {
    'inner': 'value'
  }
};

var validKeys = ['outer', 'inner'];
var invalidKeys = ['outer', 'inner', 'extra'];

console.log('Setting valid keys');
setVal(obj, validKeys, 'new value');
console.log(obj);

console.log('Setting invalid keys');
setVal(obj, invalidKeys, 'new value');
console.log(obj);
&#13;
&#13;
&#13;

如果您希望方法只更新现有键值而不设置新键值,则可以使用hasOwnProperty将最后一个语句包装在setVal中:

// if object already has the last key, update its value
if (o.hasOwnProperty(keys[len - 1])) {
  o[keys[len - 1]] = value;
} else {
  // throw an error or return false since the last key doesn't exist.
}

答案 1 :(得分:0)

这里的关键点是可以使用属性名称字符串访问对象属性:obj.prop&lt; =&gt; obj["prop"]

function SetValueByKeyNames(obj, keys, value) {
  var target = obj;
  for(var i = 0; i < keys.length - 1; i++) {
    target = target[keys[i]];
    if (!target)
      return false;
  }
  target[keys[keys.length - 1]] = value;
  return true;
}

var obj = {'outer': {'inner': 'value'} };
var keys = ['outer', 'inner'];

console.log(obj.outer.inner); // value
SetValueByKeyNames(obj, keys, 'newValue');
console.log(obj.outer.inner); // newValue