Convert array of objects to an object of arrays in JavaScript


The problem statement says to perform a complete conversion of array of objects into an object of arrays in JavaScript where array of objects are given as an input source by the user and given input can be totally converted into the resultant object of arrays successfully.

What is an array in JavaScript ?

If you are familiar with any other programming language like C, C++, or Java, you must have heard the term 'array.'

In programming, an array is a collection of similar data elements under one roof.

Now, an important question arises: if arrays are generally the same in all languages, then how does JavaScript make arrays more unique and usable?

Let's understand the overall working of arrays in JavaScript.

An array is an object that stores multiple elements. Since an array is also an object, it has some properties and methods that make working with arrays easier in JavaScript.

Following is the syntax to define Arrays in JavaScript : −

const arrayExample  = [ 2 , 3 , 5 ,6 ];
console.log(arrayExample);

Output

[2, 3, 5, 6]

What is an Object in JavaScript ?

An object in javascript is a collection of key and value pairs where the key and value pairs are called as properties of the object . Also properties of the object can be a function or a method as well. The user can easily define his own custom object as well.

Following is the syntax to define objects in JavaScript : −

const student = 
{
    name : "Ashish",
    course : "Javascript",
    from : "tutorialspoint",
    display : function(){
        console.log(student.name + " " + "is learning" + " " + student.course + " from " + student.from)
    }
}

student.display()

Output

Ashish is learning Javascript from tutorialspoint

What is an array of objects in Javascript ?

An array is an ordered collection of data whereas the objects are an unordered collection of data as objects for example represent the properties of a car , the array of objects represent specific properties of all types of car . Thus an array of objects is an ordered collection of more than one object inside it.

The syntax for array of objects looks like :

let studentArray = [
  {
    "name": "priya",
    "course": "JS",
    "from": "tutorialspoint",
    
  },
  {
    "name": "ashish",
    "course": "React",
    "from": "tutorialspoint",
  },
  {
    ...
  },
  ...
]

What is the object of Arrays in Javascript ?

In JavaScript , an object sets the properties of a real world entity , the real world entity can sometimes accumulate the array of elements for a certain key value pair as well thus forming the object of arrays concept in javascript , it makes the object complex and rigid with a good amount of data .

The syntax for object of Arrays looks like :

let studentObject = 
  {
    "name": "priya",
    "course": ["JS", "React","Python" ,"CSS"],
    "from": "tutorialspoint",
    
  }

console.log(studentObject);

Algorithm

Step 1 − Declare a function with the name objectToArrayConversion that takes in an array of objects as a parameter .

Step 2 − We need a conversion from array of objects to object of array , so for that a resultantObject is needed which is declared as an empty object.

Step 3 − For loop is used to traverse an array of object till its length property such that keys of the array of object can be extracted out using the Object.keys method.

Step 4 − Once all the keys are extracted out , we can traverse till the length of all the keys present in array of object such that if the resultObject owns that particular key using hasOwnProperty method in javascript that pushes the value pair pf the corresponding key present in the resultObject .

Step 5 − If the key is not present in the resultObject , the particular key-value pair will be assigned to the resultObject .

Step 6 − Once all the loops are over , the resultObject is returned with all key and value pair taking the shape of array assigning multiple values to the particular key of array of objects.

Example

function objectToArrayConversion(arrayOfObject)
{
    const resultObject = { };
    for(let i =0 ; i<arrayOfObject.length ; i++ )
    {
        const keys = Object.keys(arrayOfObject[i])
        for(let j = 0 ; j<keys.length ; j++)
        {
            if(resultObject.hasOwnProperty(keys[j]))
            {
                 resultObject[keys[j]].push(arrayOfObject[i][keys[j]]);
            }
            else 
            {
                resultObject[keys[j]] = [arrayOfObject[i][keys[j]]];
            }
        }
    }
    return resultObject;
}

let studentArray = [
  {
    "name": "priya",
    "course": "JS",
    "from": "tutorialspoint",
    
  },
  {
    "name": "ashish",
    "course": "React",
    "from": "tutorialspoint",
  }
  ]

  console.log(objectToArrayConversion(studentArray))

The particular code using above algorithm looks like this in console with respect to the problem statement :

Output

{
  name: [ 'priya', 'ashish' ],
  course: [ 'JS', 'React' ],
  from: [ 'tutorialspoint', 'tutorialspoint' ]
}

Time and Space Complexity

The following problem statement is solved using javascript methods like Object.keys and hasOwnProperty method that traverses the array of elements in O(n) worst case time complexity . The space complexity of the problem statement is O(1) .

Conclusion

This is how we can solve the above problem statement thinking logically and in the context of coding taking help of javascript methods in its most efficient use case .

Updated on: 21-Aug-2023

306 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements