动态访问多级对象密钥

时间:2019-08-19 20:30:57

标签: javascript javascript-objects

我有一个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"]

有什么方法可以使用数组访问所需的值?

这是我第一次问一个问题,所以如果我搞砸了,或者有什么不清楚的地方或需要更改的地方,我表示歉意。

谢谢!

4 个答案:

答案 0 :(得分:2)

是的。您可以在数组上使用reduce:

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

答案 1 :(得分:0)

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

这应该有效

答案 2 :(得分:0)

这里是一种方法:

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

答案 3 :(得分:0)

您可以使用类似的递归函数

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

相关问题