Formatting dynamic json array JavaScript


Let’s say, we have an array of objects like this −

const arr = [
   {"name1": "firstString"},
   {"name2": "secondString"},
   {"name3": "thirdString"},
   {"name4": "fourthString"},
   {"name5": "fifthString"},
   {"name6": "sixthString"},
];

We are required to write a function that takes one such array of objects and returns an object with all the properties listed in that object.

So, let’s write the code for this function. It can be done through the Array reduce method −

Example

const arr = [
   {"name1": "firstString"},
   {"name2": "secondString"},
   {"name3": "thirdString"},
   {"name4": "fourthString"},
   {"name5": "fifthString"},
   {"name6": "sixthString"},
];
const reduceArray = arr => {
   return arr.reduce((acc, val) => {
      Object.assign(acc, val);
      return acc;
   }, {});
};

Output

The output in the console will be −

{
   name1: 'firstString',
   name2: 'secondString',
   name3: 'thirdString',
   name4: 'fourthString',
   name5: 'fifthString',
   name6: 'sixthString'
}

Updated on: 26-Aug-2020

606 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements