下面是我的例子。我在Javascript中有一个动态更改的对象。在这种情况下,我想要"inside“属性的值,我知道它的位置是a[something][anotherthing][inside]
。因为我将位置保存在数组["a","somethig", "anotherthing"]
中。我的问题是如何使用数组中的键移动到该位置?我已经尝试过连接元素,最终的结果类似于这个myObject[a][somthing][anotherthing]
,但问题是它返回了'undefined‘,因为它是一个字符串。有没有可能将其转换为object,或者以某种方式在object中获得该位置?
var myarray = ['a', 'something', 'anotherthing'];
myObject = {
a: {
something: {
anotherthing: {
inside: 10
}
}
},
b: {
insideb: {}
}
}
发布于 2018-08-08 01:16:15
使用reduce将数组减少为单个值。您将传入myObject
作为起点(第二个参数),然后使用这个基本回调(第一个参数):
(obj, itm) => obj[itm]
当你把它们放在一起时,它看起来是这样的:
var myarray = ['a', 'something', 'anotherthing'];
myObject = {
a: {
something: {
anotherthing: {
inside: 10
}
}
},
b: {
insideb: {
}
}
}
let result = myarray.reduce((obj, itm) => obj[itm], myObject)
console.log(result)
console.log(result.inside)
发布于 2018-08-08 01:51:23
如果你知道这个值的确切位置:myObject['a']['somthing']['anotherthing']
会给你这个值。
如果需要动态遍历对象,可以使用:Object.keys(myObject).forEach(key => myObject[key]);
来获取顶级键。
https://stackoverflow.com/questions/51732135
复制相似问题