Make strings in array become keys in object in a new array in JavaScript?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Let’s say the following is our array −

var values = ['studentNames', 'studentMarks'];

You can use map() to convert the above array to a new array (keys in object) −

var convertIntoNewArray = values.map(arrayObject => ({ [arrayObject]: [] }));

Example

Following is the code −

var values = ['studentNames', 'studentMarks'];
console.log(values);
var convertIntoNewArray = values.map(arrayObject => ({ [arrayObject]: [] }));
console.log(convertIntoNewArray);

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

node fileName.js.

Here, my file name is demo281.js.

Output

This will produce the following output on console −

PS C:\Users\Amit\javascript-code> node demo281.js
[ 'studentNames', 'studentMarks' ]
[ { studentNames: [] }, { studentMarks: [] } ]
raja
Published on 09-Nov-2020 08:15:19
Advertisements