为了账号安全,请及时绑定邮箱和手机立即绑定

动态访问多级对象键

动态访问多级对象键

慕盖茨4494581 2021-09-17 12:47:13
我有一个 JavaScript 对象,它是多层次的,例如:let obj = [    {        "testKeyOne": "one",        "testKeyTwo": "two"    },    {        "testKeyThree": "three",        "testKeyFour": "four",        "testKeyFive": {            "testKeyFiveAndAHalf": "5.5"            "testKeyFiveAndThreeQuarters": "5.75"        }    },]我还有一个用于我需要访问的键的数组,例如,如果我正在寻找那个5.5,let array = [1, "testKeyFive", "testKeyFiveAndAHalf"]虽然我的阵列也可能看起来像这样,如果我正在寻找 "one"let array = [0, "testKeyOne"]有没有办法使用数组来访问所需的值?这是我第一次提问,所以如果我搞砸了,或者有什么不清楚的地方或需要改变的地方,我深表歉意。谢谢!
查看完整描述

3 回答

?
烙印99

TA贡献1829条经验 获得超13个赞

是的。你可以在数组上使用一个reduce:

let result = array.reduce((value, entry) => value[entry], obj);


查看完整回答
反对 回复 2021-09-17
?
HUH函数

TA贡献1836条经验 获得超4个赞

let desired = obj; 

while(array.length > 0) { desired = desired[array[0]]; array.shift() }

console.log(desired)

这应该有效


查看完整回答
反对 回复 2021-09-17
?
牧羊人nacy

TA贡献1862条经验 获得超7个赞

这是一种方法:


let obj = [{

    "testKeyOne": "one",

    "testKeyTwo": "two"

  },

  {

    "testKeyThree": "three",

    "testKeyFour": "four",

    "testKeyFive": {

      "testKeyFiveAndAHalf": "5.5",

      "testKeyFiveAndThreeQuarters": "5.75"

    }

  },

]


let arr = [

  [1, "testKeyFive", "testKeyFiveAndAHalf"],

  [0, "testKeyOne"]

]


function foo(objArr, accessArr) {

  for (const [index, ...keys] of accessArr) {

    let obj = objArr[index];

    for (const key of keys) {

       obj = obj[key];

    }

    console.log(obj)

  }

}


foo(obj, arr);


查看完整回答
反对 回复 2021-09-17
  • 3 回答
  • 0 关注
  • 200 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信