0

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}
    }
]
4
  • arr.map((v, k) => ({[v.level]: v})); your code should give the result Commented Jun 9, 2021 at 10:41
  • @Rajdeep Debnath It doesn't. Commented Jun 9, 2021 at 10:46
  • The result you're expecting is impossible, you need an object, not an array. { 2: { id: 1, level: 2 }, 3: {id: 2, level: 3 } } Commented Jun 9, 2021 at 10:47
  • @Petyor put it in snippet in the question, you will see your expected result. Commented Jun 9, 2021 at 10:49

2 Answers 2

1

You need to populate a new array using reduce:

arr.reduce((prev, curr) => { prev[curr.level] = curr; return prev }, [])
Sign up to request clarification or add additional context in comments.

Comments

0

I think I prefer the reduce method, but you could also construct an "array-like" (i.e. an object with numeric keys and a length property) and pass it to Array.from

const maxIdx = Math.max(...arr.map(v => parseInt(v.level, 10)))
const arrLen = maxIdx + 1;
const arrayLike = { 
    ...Object.fromEntries(arr.map(v => [v.level, v])), 
    length: arrLen
};
const mappedArray = Array.from(arrayLike);

For output of

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.