Dynamically access multi-level object key [duplicate]

左心房为你撑大大i 提交于 2019-12-24 11:17:32

问题


I have a JavaScript object, that is multiple levels deep, for example:

let obj = [
    {
        "testKeyOne": "one",
        "testKeyTwo": "two"
    },
    {
        "testKeyThree": "three",
        "testKeyFour": "four",
        "testKeyFive": {
            "testKeyFiveAndAHalf": "5.5"
            "testKeyFiveAndThreeQuarters": "5.75"
        }
    },
]

I also have an array for the key of what I need to access, for example, if I'm looking for the 5.5 one,

let array = [1, "testKeyFive", "testKeyFiveAndAHalf"]

though my array may also look like this if I'm looking for "one"

let array = [0, "testKeyOne"]

Is there any way to use the array to access the desired value?

This is my first time asking a question so if I messed up or if there is anything unclear or something that needs to be changed I apologize.

Thank you!


回答1:


Yep. You can just use a reduce on the array:

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



回答2:


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

this should work




回答3:


Here's one way to do it:

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);



回答4:


You can use a recursive function like that

let obj = [{
    testKeyOne: "one",
    testKeyTwo: "two"
  },
  {
    testKeyThree: "three",
    testKeyFour: "four",
    testKeyFive: {
      testKeyFiveAndAHalf: "5.5",
      testKeyFiveAndThreeQuarters: "5.75"
    }
  }
];

let array = [1, "testKeyFive", "testKeyFiveAndAHalf"];

function getValue(arr, obj) {
  const [first, ...rest] = arr;
  return typeof(obj[first]) === "object" ? getValue(rest, obj[first]) : obj[first];
}

console.log(getValue(array, obj));


来源:https://stackoverflow.com/questions/57563560/dynamically-access-multi-level-object-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!