How to store objects in array?
P粉744691205
P粉744691205 2024-04-02 18:41:14
0
2
430

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粉744691205
P粉744691205

reply all(2)
P粉080643975

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);
P粉827121558

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)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template