1

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 ?

6
  • Why do you use JSON.parse? There is no JSON there. And what is your expected result? Did you check the documentation of push? Commented Mar 5, 2021 at 8:08
  • if I do not use JSON.parse, there is still same error Commented Mar 5, 2021 at 8:09
  • there's no such thing as a JSON object - JSON is a string notation of an object, but not an object Commented Mar 5, 2021 at 8:09
  • Yes, but you should not just try and try. First make clear what you want to do and then think how you will do it. Commented Mar 5, 2021 at 8:10
  • .push({}), you forgot the curly brackets Commented Mar 5, 2021 at 8:10

3 Answers 3

2

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

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

Comments

2

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.

Comments

2
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"
  },
  ...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.