[英]Index an object multiple levels deep with one variable
我有一个对象:
object.day.time
我需要在其中访问时间属性。
由于函数的性质,我只能访问基础对象。 IE浏览器
function access(property){
let item = object[property]
// Do a lot of stuff with item
}
我不想重写该函数,因为主要用例是访问一级对象。 IE一天的财产。 有什么办法可以使这项工作吗?
我唯一能想到的是:
property = [['day']['time']]
但这没用。
编辑:我最初有对象作为访问这是错误的参数。 在这种情况下,我可以将object.day作为值传递
您可以在以下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));
希望这对您有所帮助。
调用此函数时,传递object.day而不是仅传递基础对象,这意味着函数中的对象已经是object.day,因此,如果执行object.time,则应获取该值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.