Home  >  Q&A  >  body text

How to store objects in array?

I have two arrays and I want to store them in an 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 to loop through it to make it like this, since my array is quite long and entering it manually would be cumbersome. Thanks.

P粉744691205P粉744691205188 days ago369

reply all(2)I'll reply

  • P粉080643975

    P粉0806439752024-04-03 17:40:08

    Since the length of the two arrays is the same, it can be achieved using the map function.

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

    reply
    0
  • P粉827121558

    P粉8271215582024-04-03 12:35:13

    You can use Array.map like this:

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

    reply
    0
  • Cancelreply