skip to Main Content

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


  1. You can convert an array of objects into an object with the desired structure using JavaScript. Here’s one way to do it:

    const arr = [
        {year: 2023, language: 'react'},
        {year: 2023, language: 'node'},
        {year: 2022, language: 'mongodb'},
        {year: 2022, language: 'javascript'},
        {year: 2021, language: 'jquery'},
    ];
    
    const obj = {};
    
    arr.forEach(item => {
        if (obj[item.year]) {
            obj[item.year].push(item.language);
        } else {
            obj[item.year] = [item.language];
        }
    });
    
    console.log(obj);
    

    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.

    Login or Signup to reply.
  2. You can achieve this with Javascript’s reduce() method

    const obj = arr.reduce((acc, item) => {
        if (!acc[item.year]) {
            acc[item.year] = [];
        }
        acc[item.year].push(item.language);
        return acc;
    }, {});
    
    console.log(obj)
    

    Result

    {
        '2023': ['react', 'node'],
        '2022': ['mongodb', 'javascript'],
        '2021': ['jquery']
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search