Home > Back-end >  How to convert array to object array with custom key in typescript?
How to convert array to object array with custom key in typescript?

Time:11-30

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!

CodePudding user response:

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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related