Search code examples
javascriptloopsobjectdata-conversion

is it possible to create an Object in javascript from looping data in array?


just like the title said. i want to create a new object from data inside array below: the name of the object is the first and last name.

//this is the input
arrayToObject([['Christ', 'Evans', 'Male'], ['Robert', 'Downey', 'Male']]);

//this is output that i want

// 1. Christ Evans:
// { firstName: 'Christ',
//   lastName: 'Evans',
//   gender: 'Male',

// 2. Robert Downey:
// { firstName: 'Robert',
//   lastName: 'Downey',
//   gender: 'Male',


// this is code that i write
function arrayToObject(arr) {
  
  let ObjName=""
  for (let i = 0; i<arr.length;i++){
    
  
      let firstName=arr[i][0]
      let lastName=arr[i][1]
      let ObjName=firstName.concat(' ',lastName)
      let gender=arr[1][2]

      ObjName = { // idk how to make the object.
          'firstName':firstName,
          'lastName':lastName,
          'gender':gender,
          
      }
  }
  
}

im struggling in the part where i can declare the object.


Solution

  • You could take a nested approach with Object.fromEntries and map the properties with a keys array.

    var data = [['Christ', 'Evans', 'Male'], ['Robert', 'Downey', 'Male']],
        keys = ['firstName', 'lastName', 'gender'],
        result = Object.fromEntries(data.map(a => [
            a.slice(0, 2).join(' '),
            Object.fromEntries(keys.map((k, i) => [k, a[i]]))
        ]));
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }