2

I have javascript object like following:

var endpoints = {
  User: { 
    endpoint: '/api/v1/users/%s',
    subResources: {
      profile: {
       // IN BELOW LINE I WANT TO ACCESS PARENT OBJECT'S Property
       endpoint: endpoints.User.endpoint + '/profile'
      }
    }
  }
}

this object has a object called 'User' which has property called endpoint i want to access this property in it's child object called subResources.endpoint.

1
  • You will have to do it after you've initialised the object.
    – George
    Jan 18, 2018 at 10:29

2 Answers 2

5

It is not possible, as the endpoints object itself is not fully formed yet.

So, you can do this in two steps, like this

var endpoints = {
  User: {
    endpoint: '/api/v1/users/%s',
    subResources: {}
  }
};

endpoints.User.subResources.profile = {
  endpoint: endpoints.User.endpoint + '/profile'
};
2

A different approach would be, to use a method/function:

var endpoints = {
    User: {
        endpoint: '/api/v1/users/%s',
        subResources: {
            profile: {
                endpoint: function(){
                   return endpoints.User.endpoint + '/profile';
                }
            }
        }
    }
};

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.