What is the best way to convert:
from
['firstName','lastName','gender']
to
0: {title: "firstName"}
1: {title: "lastName"}
2: {title: "gender"}
in JavaScript
What is the best way to convert:
from
['firstName','lastName','gender']
to
0: {title: "firstName"}
1: {title: "lastName"}
2: {title: "gender"}
in JavaScript
You can use .map()
to get the desired output:
const data = ['firstName','lastName','gender'];
const result = data.map(name => ({ title: name }));
console.log(result);
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)
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);