Reputation: 940
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. I.E.
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. I.E. the day property. 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
Upvotes: 2
Views: 1298
Reputation: 3321
When you call this function pass object.day instead of just the base object which means the object in the function will already be object.day so if you do object.time, you should get the value.
Upvotes: 0
Reputation: 4256
You could do sometime like this to go to this time
property:
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.
Upvotes: 1