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] }
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] }
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);
[${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);