SefaUn
SefaUn

Reputation: 1200

Create a Json Object Name With Dynamic String Variable

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

Answers (3)

mtkopone
mtkopone

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 })
}

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#new_notations_in_ecmascript_2015

Upvotes: 2

N. Mihajlovic
N. Mihajlovic

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

trincot
trincot

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

Related Questions