Alan
Alan

Reputation: 1287

How to add an object to an object array in javascript

I have this object

chartData = {
  datasets: []
};

It is meant to store datasets for Chart.js. I use this code to build the datasets from form input:

formData[index].value.forEach(function (value, dataset_index) {
      let data = {};
      data[formData[index].name] = value;
      chartData.datasets[dataset_index] = data;
});

I want chartData.datasets to have this structure:

datasets: [{
      label: 'apples',
      data: [12, 19, 3, 17, 6, 3, 7],
      backgroundColor: "rgba(153,255,51,0.4)"
    }, {
      label: 'oranges',
      data: [2, 29, 5, 5, 2, 3, 10],
      backgroundColor: "rgba(255,153,0,0.4)"
    }]

Using the debugger I see that the line

"chartData.datasets[dataset_index] = data;"

overwrites the value at chartData.datasets[dataset_index] after the first loop iteration.

So I think "I need to push "data" onto the array object". Wrong. When I try

chartData.datasets[dataset_index].push(data);

I get

TypeError: chartData.datasets[dataset_index] is undefined

Does someone know what is the proper way to add the "data" object to my chartData.datasets array? I have tried all permutations of notation to no avail. I am assuming that Array methods are not available to me because chartData.datasets[dataset_index] is an object? Search results have proven fruitless.

Update: Yes I thought about that but it doesn't work. Then you get chartData.datasets with four array elements. I want only two elements. See the data structure in the question. Also I have a snapshot of debug console after stepping thru with your suggestion. As you can see that is not the same data structure as the one I wanted. Debug console

Update II: Here is snapshot of serialized array of form input: enter image description here Hope this helps.

Update III: here is formData[index].value snapshot formData[index].value

Upvotes: 1

Views: 210

Answers (1)

Ayoub
Ayoub

Reputation: 1435

you need to push the data into datasets array:

chartData.datasets.push(data)

following my understanding of what did you describe here is a solution:

formData[index].value.forEach(function(value, dataset_index) {
  let data = {};
  data[formData[index].name] = value;
  chartData.datasets[dataset_index] = Object.assign(chartData.datasets[dataset_index] || {}, data);
});

Hope this will work for you!

Upvotes: 4

Related Questions