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!
>Solution :
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);