Transform nested array into normal array with JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

Let’s say the following is our nested array −

const arrayObject = [
   [
      {
         Name: "John"
      },
      {
         countryName: "US"
      }
   ],
   [
      {
         subjectName: "JavaScript"
      },
      {
         teacherName: "Mike"
      }
   ]
];

To transform nested array into normal array, use the concept of flat() as in the below code −

Example

const arrayObject = [
   [
      {
         Name: "John"
      },
      {
         countryName: "US"
      }
   ],
   [
      {
         subjectName: "JavaScript"
      },
      {
         teacherName: "Mike"
      }
   ]
];
const output = arrayObject.flat();
console.log(output);

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

node fileName.js.

Here, my file name is demo50.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo50.js
[
   { Name: 'John' },
   { countryName: 'US' },
   { subjectName: 'JavaScript' },
   { teacherName: 'Mike' }
]
raja
Published on 03-Sep-2020 09:56:51
Advertisements