-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?

1
  • you should really gives some code of what you have tried or you won't learn, we are not here to do your homework Commented Jan 5, 2018 at 15:50

1 Answer 1

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);

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.