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] }
tsujp
  • 1,066
  • 1
  • 12
  • 29
  • There's no such syntax. If `property` is the only thing about the path that's dynamic, only use that in a computed key. – Cerbrus Nov 07 '17 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. – Olivier Butler Nov 07 '17 at 12:28

2 Answers2

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
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);
kind user
  • 40,029
  • 7
  • 67
  • 77