-3

I have an array of objects as below;

{
    'data': [{
            value: 1000,
            year: 1990
        },
        {
            value: 1001,
            year: 1990
        },
        {
            value: 1002,
            year: 1990
        },
        {
            value: 1003,
            year: 1991
        },
        {
            value: 1004,
            year: 1991
        }
    ]
}

I want to convert the same to the one looks like below object

{
    '1990': [{
            value: 1000,
            year: 1990
        },
        {
            value: 1001,
            year: 1990
        },
        {
            value: 1002,
            year: 1990
        }],

    '1991':[{
            value: 1003,
            year: 1991
        },
        {
            value: 1004,
            year: 1991
        }
    ]
}

Is there any way for doing the same in Javascript or Angular 4?

BKM
  • 6,949
  • 7
  • 30
  • 45
  • you should really gives some code of what you have tried or you won't learn, we are not here to do your homework – DarkMukke Jan 05 '18 at 15:50

1 Answers1

2

Use Array#reduce function to iterate over each item and check if the accumulate object does not contain a property with that key, add it, assign to it an array an then push the item into it. If contains, just push the item.

const data = [{
            value: 1000,
            year: 1990
        },
        {
            value: 1001,
            year: 1990
        },
        {
            value: 1002,
            year: 1990
        },
        {
            value: 1003,
            year: 1991
        },
        {
            value: 1004,
            year: 1991
        }
    ];
    
const mapped = data.reduce((acc, item) => {
   
   if(!acc.hasOwnProperty(item.year)) {
      acc[item.year] = [];
   }
   
   acc[item.year].push(item);
   
   return acc;
    
}, {});

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