首页 > 解决方案 > 按路径访问嵌套属性

问题描述

我正在尝试从字符串访问对象的嵌套属性。

这是我的示例代码:

var obj = {
  'text': 'hello',
  'foo': {
    'float': 0.5,
    'bar': {
      'id': 42
    }
  }
};

var keyOne = 'text';
var keyTwo = 'foo.float';
var keyThree = 'foo.bar.id';

console.log(obj[keyOne]); // successfully log 'hello'
console.log(obj[keyTwo]); // trying to log '0.5'
console.log(obj[keyThree]); // trying to log '42'

我正在尝试在 JS 中执行此操作,但我也为 jQuery 准备了更清洁的解决方案。

标签: javascriptjquerypropertiesnested

解决方案


为此,您必须进行一些遍历。

通过 it's分割路径.,然后Array.reduce在每次迭代时通过括号访问器访问它所引用的属性的部分。

最终你会达到你所追求的价值。

var obj = {
  'text': 'hello',
  'foo': {
    'float': 0.5,
    'bar': {
      'id': 42,
      'baz': [{ name: 'Mary' }, { name: 'Jane' }]
    }
  }
};

var getValueByPath = (obj, path) =>
  path.split('.').reduce((acc, part) => acc ? acc[part] : undefined, obj);

var keyOne = 'text';
var keyTwo = 'foo.float';
var keyThree = 'foo.bar.id';
var keyFour = 'foo.bar.baz.1.name';

console.log(getValueByPath(obj, keyOne));
console.log(getValueByPath(obj, keyTwo));
console.log(getValueByPath(obj, keyThree));
console.log(getValueByPath(obj, keyFour));


推荐阅读