Wrap Object Properties of Type String with Arrays in JavaScript



For this, use Object.keys() along with reduce(). To display the result, we will also use concat().

Example

Following is the code −

var details = { name: ["John", "David"], age1: "21", age2: "23" },
   output = Object
      .keys(details)
      .reduce((obj, tempKey) =>
         (obj[tempKey] = [].concat(details[tempKey]), obj), {})
console.log(output)  

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

node fileName.js.

Here, my file name is demo302.js.

Output

This will produce the following output on console −

PS C:\Users\Amit\javascript-code> node demo302.js
{ name: [ 'John', 'David' ], age1: [ '21' ], age2: [ '23' ] }
Updated on: 2020-11-09T11:17:24+05:30

512 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements