0

I am trying to dynamically create the following object

let foo = {
    bar: {
        data: [1, 2, 3]
    }
}

Is there a way to correct this statement to achieve this?

let property = bar
foo = { [`${property}/data`]: [1, 2, 3] }
2
  • There's no such syntax. If property is the only thing about the path that's dynamic, only use that in a computed key. Commented Nov 7, 2017 at 12:21
  • You should clarify what bar is, and what you're trying to achieve overall. As it stands, it's hard to see whether you're asking about a specific case of an object with a single property, itself an object, or as part of larger example. I'd certainly caution against trying to do it on one line until you have it working in some form at least. Commented Nov 7, 2017 at 12:28

2 Answers 2

3

You could only take property for a computed property name and take the rest as object.

var property = 'bar',
    foo = { [property]: { data: [1, 2, 3] } };

console.log(foo);

For a double nested object, you could take the other data property as variable as well.

var property0 = 'bar',
    property1 = 'data',
    foo = { [property0]: { [property1]: [1, 2, 3] } };

console.log(foo);

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

Comments

1

[${property}/data] won't create a nested object inside.

Anyways, bar isn't defined and will throw an error.

Use following approach:

let property = 'bar';

let foo = { [property]: { 
    data: [1,2,3],
  } 
};

console.log(foo);

1 Comment

I think bar may be referring to 'some other predefined variable'

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.