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

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

1 Answer 1

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!

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

1 Comment

@alan can you provide a sample data example of formData[index].value

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.