Reputation: 557
I am learning typescript. It might be a silly question, but I am not able to find the answer online. I would like to convert an array to an object array (values are from the array). For example:
Input:
const array = ["Tom", "Jack", "Rose"]
Expected ouput:
[
{
name: "Tom",
initial: "t",
year: "2021"
},
{
name: "Jack",
initial: "j",
year: "2021"
},
{
name: "Rose",
initial: "r",
year: "2021"
},
]
What is the best way to achieve this in typescript?
Thanks!
Upvotes: 1
Views: 1428
Reputation: 31
Maybe even easier:
const array = ['Tom', 'Jack', 'Rose'];
const arrayOfObjects = array.map(element => {
return {
name: element,
initial: element.charAt(0),
year: new Date().getFullYear().toString(),
};
});
console.log(arrayOfObjects);
Upvotes: 3
Reputation: 1384
This maybe the easiest way:
const array = ["Tom", "Jack", "C"]
const newObj = [];
array.forEach(eachArrayElement => {
const x = {
name: eachArrayElement,
initial: eachArrayElement[0].toLowerCase(),
year: (new Date().getFullYear()).toString()
};
newObj.push(x);
})
console.log('New Obj ==>', newObj);
Upvotes: 4