0

What is the best way to convert:

from

['firstName','lastName','gender']

to

0: {title: "firstName"}
1: {title: "lastName"}
2: {title: "gender"}

in JavaScript

3 Answers3

1

You can use .map() to get the desired output:

const data = ['firstName','lastName','gender'];

const result = data.map(name => ({ title: name }));

console.log(result);
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
-1

Try this code.I hope it will helps you.

var arr = ['firstName','lastName','gender']

var jsonObj = {};
for (var i = 0 ; i < arr.length; i++) {
    jsonObj['title' +(i+1) ] = arr[i];
}
console.log(jsonObj)
Pushprajsinh Chudasama
  • 7,772
  • 4
  • 20
  • 43
-2

You can simply use forEach() loop which is the easiest way:

var arr = ['firstName','lastName','gender'];

let res = [];
arr.forEach((item) => res.push({title: item}));
console.log(res);

Just to build your knowledge in Array operations you can also use reduce():

var arr = ['firstName','lastName','gender'];

let res = arr.reduce((acc, item) => {
  acc.push({title: item});
  return acc;
}, []);
console.log(res);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62