2

I am trying to use a dynamic name for a property of an object.

For example, in the function below, I want to use the value of variable 'catagoryId' to get the child that results into the value for the variable catagoryId. For example if catagoryId = book. I want the last line to resolve to "endAtObject.orderValues.book".

        export const feedFetch = (catagoryId, endAtObject) => {
        endAtObject.orderValues.<<<catagoryId>>> 
        }

How do I do this? Any help will be highly appreciated!

3
  • unless I'm missing something, this is plain JS: endAtObject.orderValues[categoryId] Commented Dec 10, 2016 at 4:22
  • If I do that I am getting an unexpected token error. Basically my endAtObject object has a child named orderValue and that has different childs with different names. In the example I am trying to get to a child named book. Commented Dec 10, 2016 at 4:27
  • drewmoore's comment is the correct way of doing it. Just make sure that order values is an Object, not a JSON string or array etc Commented Dec 10, 2016 at 7:09

1 Answer 1

3

What you're looking for is 'computed property names'. This will do the job.

export const feedFetch = (catagoryId, endAtObject) => {
    endAtObject.orderValues[catagoryId]
}

You can find more info at https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Object_initializer (CMD+F "Computed property names")

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

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.