-1

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.

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
QrQr
  • 141
  • 1
  • 13

2 Answers2

-1

I would suppose you want an array of objects with the following structure:

[
  {
    "firstName": "Christ",
    "lastName": "Evans",
    "gender": "Male"
  },
  {
    "firstName": "Robert",
    "lastName": "Downey",
    "gender": "Male"
  }
]

If that's the case, you can simply use Array.prototype.map, and in the callback you simply use array destructuring to unpack the second level array into firstName, lastName and gender:

function arrayToObject(arr) {
  return arr.map((entry) => {
    const [firstName, lastName, gender] = entry;
    return {
      firstName,
      lastName,
      gender
    };
  });
}

const a = arrayToObject([['Christ', 'Evans', 'Male'], ['Robert', 'Downey', 'Male']]);
console.log(a);
Terry
  • 63,248
  • 15
  • 96
  • 118
-1

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392