Reputation: 1200
I want to code an object name with a dynamic string variable.
this.datas: [
{
name: "john",
data: 10
}
{
name: "add",
data: 20
}
]
this.latestBarChart: {
chartName: "Line",
style: "red"
}
for (let i = 0; i < this.datas.length; i++) {
this.screenData[i].data.push(JSON.parse(`${this.datas[i].name}`: this.latestBarChart));
}
I tried like this. But there is an error because of this :
while I push
this.screenData[i].data.push(JSON.parse(`${this.datas[i].name}`: this.latestBarChart));
How can I do this ?
Upvotes: 1
Views: 1310
Reputation: 6443
If you are using ES6 you can use the computed key syntax like this:
for (let i = 0; i < this.datas.length; i++) {
this.screenData[i].data.push({ [this.datas[i].name]: this.latestBarChart })
}
Upvotes: 2
Reputation: 36
I think you want to do this.
for (let i = 0; i < this.datas.length; i++) {
this.screenData[i].data.push({
[this.datas[i].name]: this.latestBarChart
});
}
This will create array with objects inside screenData.data. Objects would look like this.
{
john: {
chartName: "Line",
style: "red"
},
...
}
Upvotes: 2
Reputation: 351183
It looks like you want to do this:
this.screenData[i].data.push({ [this.datas[i].name]: this.latestBarChart });
Note that there is no JSON in your code, so there is no reason to use JSON.parse
.
Upvotes: 2