如何通过字符串数组遍历javascript对象?

时间:2018-06-05 01:41:01

标签: javascript

我正在尝试使用字符串数组来访问嵌套在对象中的值。

这已经有了实用工具吗?

let obj= {
  one: {
    two: {
      thee: "test"
    }
  }
}

let values= ["one", "two", "three"]

function accessObjectWithArray(obj, arr) {
    // returns "test"
}

3 个答案:

答案 0 :(得分:2)

使用reduce遍历属性数组:

const obj={one:{two:{three:"test"}}};
const values= ["one", "two", "three"];

const accessObjectWithArray = (obj, arr) => arr.reduce((a, prop) => a[prop], obj);
console.log(accessObjectWithArray(obj, values));

答案 1 :(得分:0)

没有内置到js中来做这个,但你可以做一个很好的递归函数来做到这一点:



let obj= {
  one: {
    two: {
      three: "test"
    }
  }
}

let values= ["one", "two", "three"]

function accessObjectWithArray(obj, arr) {
    if (!arr.length) return obj;
    return accessObjectWithArray(obj[arr[0]], arr.slice(1));
}

console.log(accessObjectWithArray(obj, values));




注意:我修复了three属性中的拼写错误

答案 2 :(得分:0)

lodash有一个很好的get功能:

let obj= {
  one: {
    two: {
      three: "test"
    }
  }
}

console.log(_.get(obj, ['one', 'two', 'three']))

console.log(_.get(obj, 'one.two.three'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>