Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert array to object array with custom key in typescript?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
  {
    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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading