2

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

3
  • If you only want to use your access function, you'll have to rewrite it, at least a bit. Right now, you cannot expect to access the second level, since, as you stated, it is only designed for the main use case, which is one level object. Commented May 12, 2018 at 9:11
  • 1
    Can't you just call access this way: access(object.day, 'time') ? Commented May 12, 2018 at 9:27
  • Oops. Sorry, I didn't mean to put object as a param. Commented May 12, 2018 at 9:39

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.