-1

I am having a problem to figure out in ReactJs how to access the elements from a dict in array and to build another dict. The data is like this:

[ {name: "dad", data: 10}, {name: "mom", data: 20}, {name: "dad", data: 40},
     {name: "mom", data:50}, {name: "dad", data: 01}]

I want the data to be like this:

[{name: "dad", data: [10,40,01]}, {name: "mom", data: [50,20]}]
Mihail
  • 385
  • 1
  • 6
  • 17
  • `name: dad,` Are those really standalone variables, or did you mean them to be strings? If strings, strings need delimiters. You should also post what you've tried that isn't working. – CertainPerformance May 20 '19 at 11:47
  • search provider of your choice -> _"javascript group array of objects"_ – Andreas May 20 '19 at 11:49
  • i think dictionary should be of form {dad : [], mom: []} i.e. name should be key and data array should be value for your use case. – bhavesh27 May 20 '19 at 11:49
  • [Most efficient method to groupby on a array of objects](https://stackoverflow.com/questions/14446511/most-efficient-method-to-groupby-on-a-array-of-objects) – Andreas May 20 '19 at 11:53
  • @CertainPerformance yes should be a string, just fixed this. bhavesh27 no, I should you an example how I want it to be. Andreas, let me try and will come with a reply – Mihail May 20 '19 at 12:12

1 Answers1

0

I would do something like that:

var myArray = [{name: 'dad', data: 10}, {name: 'mom', data: 20}, {name: 'dad', data: 40},{name: 'mom', data:50}, {name: 'dad', data: 1}];

   var newObject={};
   myArray.forEach((el)=>
  {
    if (newObject.hasOwnProperty(el.name))
        newObject[el.name].push(el.data);
    else
        newObject[el.name]=[el.data];   
  })

     console.log(newObject);
Luigi
  • 264
  • 1
  • 10
  • I tried grouping but is not working, I think my array when I print it it has: [0: {"mom", 20}, 1: {"dad", 30}} how can I solve this problem by having just [{}, {}]? – Mihail May 20 '19 at 13:48