skip to Main Content

I have two arrays and I want to store them in one array and create them as an object.

const name = ["Amy", "Robert", "Sofie"];
const age = ["21", "28", "25"];

The output I want is:

const person =[{name: 'Amy', age: '21'}, {name: 'Robert', age: '28'}, {name: 'Sofie', age: '25'}];

Is there a way that I can loop it to make it like this because my array is very long would be bothersome to manually type it. Thanks.

2

Answers


  1. Given that the lengths of the two arrays are the same, you can use map function to achieve this.

    const name = ["Amy", "Robert", "Sofie"];
    const age = ["21", "28", "25"];
    
    const person = name.map((nameValue, index) => {
      const ageValue = age[index];
      return { name: nameValue, age: ageValue };
    });
    
    console.log(person);
    Login or Signup to reply.
  2. You could use Array.map like:

    const names = ["Amy", "Robert", "Sofie"];
    const ages = ["21", "28", "25"];
    
    const persons = names.map((name, i) => ({name, age: ages[i]}));
    
    console.log(persons)

    Take in consideration that the arrays length have to be equal.
    And use plural when naming Arrays.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search