-2

I need to convert two arrays of strings with the same length:

const arr1 = ['Jessica', 'Ben', 'Samantha', 'John', 'Sandy'];
const arr2 = ['21', '45', '34', '90', '67']; 

And in the end i need to get this array with particular keys name, age:

const result = [
{ name: 'Jessica', age: '21'}, 
{ name: 'Ben', age: '45'}, 
{ name: 'Samantha', age: '34'},
{ name: 'John', age: '90' },
{ name: 'Sandy', age: '67' },
];

Can you tell me please how can i do it?

jocoders
  • 1,594
  • 2
  • 19
  • 54
  • of course! and i did not find a good solution, help me if you know it – jocoders Feb 27 '20 at 09:43
  • Please post your attempt for solving this, and if you face any problem with it, we can help you. – Ele Feb 27 '20 at 09:45
  • @jocoders Then please share your attempt in question. SO is not a **get code for free site** – Rajesh Feb 27 '20 at 09:47
  • but it is not the same question that you have posted! – jocoders Feb 27 '20 at 09:49
  • 1
    @jocoders, Here you can get the result you want https://codepen.io/Maniraj_Murugan/pen/KKpmKPM – Maniraj Murugan Feb 27 '20 at 09:54
  • Updated the duplicate which is same as your question – adiga Feb 27 '20 at 09:55
  • Anyone who knows how to use a loop, and how to assign object properties with “dynamic” names, should be able to easily solve this. (And anyone who lacks knowledge of either of the two, should maybe go read up on / research such basics?) – CBroe Feb 27 '20 at 09:55

1 Answers1

5

Loop through the arr1. You get the names and the index. Based on index, get the ages from arr2 considering name and age array indexes are same

const arr1 = ['Jessica', 'Ben', 'Samantha', 'John', 'Sandy'];
const arr2 = ['21', '45', '34', '90', '67']; 

const result = arr1.map((name, index) => {
  return {
    'name': name,
    'age': arr2[index]
  }
})

console.log(result)
adiga
  • 34,372
  • 9
  • 61
  • 83