Search code examples
javascriptarraysecmascript-6javascript-objects

Swap array keys with inner object value


I have this array which holds objects;

let arr = [
    {
        "id": 1,
        "level": "2",
    },
    {
        "id": 2,
        "level": "3",
    }
]

By default the array has keys starting from 0 and it looks like this:

[
    0: {id: 1, level:2},
    1: {id: 2, level:3}
]

How can I transform it so that the keys are the values of the property 'level'? It should look like this:

[
    2: {id:1, level:2},
    3: {id:1, level:3}
]

So far I have tried this but it doesn't remove the original keys:

arr.map((v, k) => ({[v.level]: v}));

So I have something like this:

[
    0: {2:
        {id: 1, level:2}
    },
    1: {3:
        {id: 2, level:3}
    }
]

Solution

  • You need to populate a new array using reduce:

    arr.reduce((prev, curr) => { prev[curr.level] = curr; return prev }, [])