Wrap object properties of type string with arrays - 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: 09-Nov-2020

429 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements