Search code examples
javascriptarraysobjectjavascript-objects

Assigning 2 arrays key value in Javascript?


I have two arrays

ar1 = ["jhon", "doe", "alex"];
ar2 = ["21", "22", "35"];

I want to convert them into an object just like following

obj=[
{name:'jhon',age:'21'},
{name:'doe', age:'22'},
{name:'alex', age:'35'}
]

how do I that in javascript?


Solution

  • You can use the map function:

    var arr1 = ["jhon", "doe", "alex"];;
    var arr2 = ["21", "22", "35"];
    
    const obj = arr1.map((item, index) => {
      return {
       name: item,
       age: arr2[index]
      }
    })
    

    On the map function, just to clean the code, you can use an implicit return:

    const obj = arr1.map((item, index) => ({
      name: item,
      age: arr2[index]
     })
    )