0

I'm trying to create a json by looping over the data that I got and here the problem is I'm able to get the values correctly, but coming to the keys, they are not getting populated as expected. Here is my code.

var item = [{
    "max": "0.575",
  "ingredients": "a",
}, {
   "max": "10.25",
  "ingredients": "b"
}, {
   "max": "98.5",
   "ingredients": "c",
 }];

var valuesForChart = {
  data: []
};

item.forEach(function(subItem) {
  var names = subItem.ingredients;
  var level = subItem.max;
  valuesForChart.data.push({
    names: level
  });
});

document.getElementById("x").innerHTML=JSON.stringify(valuesForChart);

Here item is returned from my database. when I run this, I get the output as below.

{"data":[{"names":"0.575"},{"names":"10.25"},{"names":"98.5"}]}

but my expected output is

{"data":[{"a":"0.575"},{"b":"10.25"},{"c":"98.5"}]}

very confused on where I'm going wrong. please let me know on how can I fix this.

Here is a working fiddle. https://jsfiddle.net/j8gj9uv0/2/

Thanks

user3872094
  • 3,269
  • 8
  • 33
  • 71
  • Possible duplicate of [Using a variable for a key in a JavaScript object literal](https://stackoverflow.com/questions/2274242/using-a-variable-for-a-key-in-a-javascript-object-literal) – Sebastian Simon Dec 26 '17 at 06:18

1 Answers1

4

You need to evaluate the names using [names]

When you use [] notation at the property declaration in the object, it gets an expression and sets the value of that expression as the property name. So the name is not just names but what under the names.

var item = [
    { "max": "0.575", "ingredients": "a" }, 
    { "max": "10.25", "ingredients": "b" }, 
    { "max": "98.5", "ingredients": "c" }
];

var valuesForChart = {
  data: []
};

item.forEach(function(subItem) {
  var names = subItem.ingredients;
  var level = subItem.max;
  valuesForChart.data.push({
    [names]: level
  });
});

console.log(valuesForChart);
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112