gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:59:50 25 4
gpt4 key购买 nike

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

已经有这样的实用程序了吗?

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

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

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

最佳答案

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

关于javascript - 如何通过字符串数组遍历 javascript 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50690886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com