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