Merge Array to Object Array JavaScript

后端 未结 5 1339
醉梦人生
醉梦人生 2021-01-23 09:00

I have an array here:

var array = [
    [
        [\'firstName\', \'Nork\'], [\'lastName\', \'James\'], [\'age\', 22], [\'position\', \'writer\']
    ],
    [
           


        
5条回答
  •  迷失自我
    2021-01-23 09:23

    Use [].map over [].reduce


    The map() method creates a new array with the results of calling a provided function on every element in this array.


    The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

    var array = [
      [
        ['firstName', 'Nork'],
        ['lastName', 'James'],
        ['age', 22],
        ['position', 'writer']
      ],
      [
        ['firstName', 'James'],
        ['lastName', 'Rodel'],
        ['age', 25],
        ['position', 'programmer']
      ]
    ];
    
    function mergeObjectArray(array) {
      return array.map(function(el) {
        return el.reduce(function(a, b) {
          a[b[0]] = b[1];
          return a;
        }, {})
      });
    }
    console.log(mergeObjectArray(array));

提交回复
热议问题