Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to solve this problem by using .forEach or .map instead of for-loop?

I need to write a function that converts array elements within an array into objects. Although I've figured out a way to solve the problem by using for-loop, I'm just wondering if there's more concise way to write up the solution by using methods such as forEach or map.

The problem is...

var array: [
  [
    ['firstName', 'Joe'],
    ['lastName', 'Blow'],
    ['age', 42],
    ['role', 'clerk']
  ],
  [
    ['firstName', 'Mary'],
    ['lastName', 'Jenkins'],
    ['age', 36],
    ['role', 'manager']
  ]
];

I need to convert the above array into something like this.

[
  { firstName: 'Joe', lastName: 'Blow', age: 42, role: 'clerk' },
  { firstName: 'Mary', lastName: 'Jenkins', age: 36, role: 'manager' }
];

The following is the code I've come up with by using a for-loop.

function transformEmployeeData(array)
{  
  var output = [];

  for (var i = 0; i < array.length; i++)
  {
    var obj = {};

    for (var j = 0; j < array[i].length; j++)
    {
      obj[array[i][j][0]] = array[i][j][1];
    }

    output.push(obj);
  }

  return output;
}

Like I have mentioned above, it will be great if there's another way to solve the problem.

like image 988
Damagedcase Avatar asked Apr 03 '19 15:04

Damagedcase


2 Answers

In some near future maybe you could use Object.fromEntries(). It is supported on some browsers version right now: Browser Compatibility:

var arr = [
  [
    ['firstName', 'Joe'],
    ['lastName', 'Blow'],
    ['age', 42],
    ['role', 'clerk']
  ],
  [
    ['firstName', 'Mary'],
    ['lastName', 'Jenkins'],
    ['age', 36],
    ['role', 'manager']
  ]
];

console.log(arr.map(Object.fromEntries));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
like image 89
Shidersz Avatar answered Oct 17 '22 04:10

Shidersz


You could map new objects by mapping the properties and join all properties to a single objects.

var data = [[['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']], [['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager']]],
    result = data.map(a => Object.assign(...a.map(([key, value]) => ({ [key]: value }))));
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 26
Nina Scholz Avatar answered Oct 17 '22 06:10

Nina Scholz