javascriptarraysecmascript-6array-reduce

Reduce an array to change content


How can I use array.reduce to change the way the content of the array is. I don't want to do any math on the content.

Orinal array:

var myArray = [
    {id:1, name:'name01', value:11},
    {id:2, name:'name02', value:22},
    {id:3, name:'name03', value:33},
    {id:4, name:'name04', value:44},
    {id:5, name:'name05', value:55}
]

I want it to be changed to :

[
    {1:{id:1, name:'name01', value:11}},
    {2:{id:2, name:'name02', value:22}},
    {3:{id:3, name:'name03', value:33}},
    {4:{id:4, name:'name04', value:44}},
    {5:{id:5, name:'name05', value:55}}
]

So the id is popped out of the object as a key and the value it's the entire object.

Can this be achieved with only array.reduce without using any for loop or groupBy?


Solution

  • You can use .map() instead with the ES6 calculated property name, like so:

    var myArray = [
        {id:1, name:'name01', value:11},
        {id:2, name:'name02', value:22},
        {id:3, name:'name03', value:33},
        {id:4, name:'name04', value:44},
        {id:5, name:'name05', value:55}
    ];
    
    var result = myArray.map((elem) => ({[elem.id]: elem}));
    
    console.log(result);

    Or if you insist on using .reduce():

    var myArray = [
        {id:1, name:'name01', value:11},
        {id:2, name:'name02', value:22},
        {id:3, name:'name03', value:33},
        {id:4, name:'name04', value:44},
        {id:5, name:'name05', value:55}
    ];
    
    var result = myArray.reduce((res, curr) => res.concat({[curr.id]: curr}), []);
    
    console.log(result);

    Alternatively, ES5 Syntax (for clarity since you are trying to learn)

    var result = myArray.reduce(function (res, curr) {
        var newObj = {};
        newObj[curr.id] = curr;
        return res.concat(newObj);
    }, []);