我有一个对象:
const list = {
library: {
books: {
count: 100
}
}
}
我有一个数组:
const key = [ 'library', 'books', 'count' ]
我想使用该数组从对象中获取值 100
。
我试过只使用数组:
const list = {
library: {
books: {
count: 100
}
}
}
const key = [ 'library', 'books', 'count' ]
console.log(list[key])
这里没有惊喜,返回 undefined
。
我试过将它转换成字符串:
const list = {
library: {
books: {
count: 100
}
}
}
const key = [ 'library', 'books', 'count' ]
console.log(list[key.toString()])
显然再次返回 undefined
。
我当然可以使用数组遍历对象 - 但我希望有人知道一个可爱的单行代码,它会像魔术一样工作。
最佳答案
我知道的最简洁的方法是使用reduce
:
const list = {
library: {
books: {
count: 100
}
}
}
const key = [ 'library', 'books', 'count' ]
// simple one-liner
let val = key.reduce((obj,key) => obj[key], list)
console.log(val)
当然,如果您处理的是不一致的数据,您可能需要进行一些检查。
您也可以使用递归函数,但不是那么短:
const list = {
library: {
books: {
count: 100
}
}
}
const key = [ 'library', 'books', 'count' ]
function getKey(obj, list) {
let key = list.shift()
if (key === undefined) return
let val = obj[key]
if (typeof val !== 'object') return val
return getKey(val, list)
}
let val = getKey(list, key)
console.log(val)
关于javascript - 使用 JavaScript 解析对象名称路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49758769/