Wrap object properties of type string with arrays - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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' ] }
raja
Published on 09-Nov-2020 11:17:24
Advertisements