[英]Index an object multiple levels deep with one variable
I have an object: 我有一个对象:
object.day.time
where I need to access the time property. 我需要在其中访问时间属性。
Due to the nature of the function, I only have access to the base object. 由于函数的性质,我只能访问基础对象。 IE
IE浏览器
function access(property){
let item = object[property]
// Do a lot of stuff with item
}
I don't want to rewrite the function because the main use case is accessing objects one level deep. 我不想重写该函数,因为主要用例是访问一级对象。 IE the day property.
IE一天的财产。 Is there any way I can make this work?
有什么办法可以使这项工作吗?
The only thing I could think of was: 我唯一能想到的是:
property = [['day']['time']]
but that didn't work. 但这没用。
EDIT: I originally had object as a param to access which was wrong. 编辑:我最初有对象作为访问这是错误的参数。 I that case I could just pass object.day as a value
在这种情况下,我可以将object.day作为值传递
You could do sometime like this to go to this time
property: 您可以在以下
time
执行以下操作以转到time
属性:
var object = { day: { time: (new Date()).getTime() } }; var properties = ["day","time"]; function access(object,properties){ for(var index=0; index < properties.length; index++){ // go to deeper into object until your reached time object = object[properties[index]]; } // here we have reached time and can do something with it or just returning it return object; } console.log(access(object,properties));
Hope this helps you. 希望这对您有所帮助。
调用此函数时,传递object.day而不是仅传递基础对象,这意味着函数中的对象已经是object.day,因此,如果执行object.time,则应获取该值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.