How to transform object of objects to object of array of objects with JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

To transform object of objects to object of array of objects, use the concept of Object.fromEntries() along with map().

Example

const studentDetails = {
   'details1': {Name: "John", CountryName: "US"},
   'details2': {Name: "David", CountryName: "AUS"},
   'details3': {Name: "Bob", CountryName: "UK"},
};
console.log(
   Object.fromEntries(Object.entries(studentDetails).map(([key,
   value]) => [key, [value]]))
);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo45.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo45.js
{
   details1: [ { Name: 'John', CountryName: 'US' } ],
   details2: [ { Name: 'David', CountryName: 'AUS' } ],
   details3: [ { Name: 'Bob', CountryName: 'UK' } ]
}
raja
Published on 02-Sep-2020 09:47:54
Advertisements