1

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

  • It might be good to nestle in with a JavaScript tutorial for a little bit.. – user2864740 Dec 30 '17 at 22:53
  • By all means. What JS tutorial would you suggest would help with my problem??? – Alan Dec 31 '17 at 0:36
  • stackoverflow.com/tags/javascript/info contains useful curated resources. See the "Learning JavaScript" and "Interactive JavaScript learning" sections. – user2864740 Dec 31 '17 at 0:40
4

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!

  • @alan can you provide a sample data example of formData[index].value – Ayoub Dec 30 '17 at 23:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.