How to convert an array of objects into an object. What is wrong in the code
From –
const arr = [
{year: 2023, language: 'react'},
{year: 2023, language: 'node'},
{year: 2022, language: 'mongodb'},
{year: 2022, language: 'javascript'},
{year: 2021, language: 'jquery'},
]
To –
const obj = {
'2023': ['react', 'node'],
'2022': ['mongodb', 'javascript'],
'2021': ['jquery']
}
2
Answers
You can convert an array of objects into an object with the desired structure using JavaScript. Here’s one way to do it:
This code initializes an empty object obj and then iterates through the arr array. For each item in the array, it checks if the year property already exists as a key in the obj object. If it does, it pushes the language into the existing array. If not, it creates a new array with the language and assigns it to the year key in the obj object. The result is the desired object structure.
You can modify the code according to requirement.
You can achieve this with Javascript’s
reduce()
methodResult