1

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!

3
  • Little confused from your question, are you asking how to create the object from the array or how to define that name property can only be from array [A,B,C] Commented Nov 30, 2021 at 0:10
  • I would say latter, but basically, I am asking what the best way to get the expected output from example input. I updated a bit, and hope it is less confusion now. Commented Nov 30, 2021 at 0:15
  • Checkout the map function developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Nov 30, 2021 at 0:18

2 Answers 2

4

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Use Array.map() instead of Array.forEach(). It is more appropriate for the goal (transform one array into another.)
3

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);

1 Comment

map is the way to go. Please add element.charAt(0).toLowerCase() for the sake of completeness

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.