Merge Array to Object Array JavaScript

后端 未结 5 1336
醉梦人生
醉梦人生 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:11

    See this one:

    var array = [
        [
            ['firstName', 'Nork'], ['lastName', 'James'], ['age', 22], ['position', 'writer']
        ],
        [
            ['firstName', 'James'], ['lastName', 'Rodel'], ['age', 25], ['position', 'programmer']
        ]
    ];
    
    function changeData(array)
    {
        var i,j;
        var ret = [];
        var tmp = {};
    
        // rotate through every line and create a temporary object which we push to the return array
        for (i=0;i<array.length;i++)
        {
            tmp = {};
            for (j=0;j<array[i].length;j++) tmp[ array[i][j][0] ] = array[i][j][1];
            ret.push(tmp);
        }
        return ret;
    }
    
    console.log(changeData(array));
    
    0 讨论(0)
  • 2021-01-23 09:17

    You can simply do it using Array.prototype.map() to loop over the first array along with a Array.prototype.forEach() in its callback to loop over the sub arrays and merge them in a unique object:

    var merged = array.map(function(arr) {
      var obj = {};
      arr.forEach(function(item) {
        obj[item[0]] = item[1];
      });
      return obj;
    });
    

    Demo:

    var array = [
      [
        ['firstName', 'Nork'],
        ['lastName', 'James'],
        ['age', 22],
        ['position', 'writer']
      ],
      [
        ['firstName', 'James'],
        ['lastName', 'Rodel'],
        ['age', 25],
        ['position', 'programmer']
      ]
    ];
    
    var merged = array.map(function(arr) {
      var obj = {};
      arr.forEach(function(item) {
        obj[item[0]] = item[1];
      });
      return obj;
    });
    console.log(merged);

    0 讨论(0)
  • 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));

    0 讨论(0)
  • 2021-01-23 09:27

    You have not specified how you want to merge the users. this will take your array of user objects and reduce all the results into a single object with an array of all values supplied.

    var array = [
      {firstName: 'Nork', lastName: 'James', age: 22, position: 'writer'},
      {firstName: 'James', lastName: 'Rodel', age: 25, role: 'programmer'}
    ]
    
    function changeData(array) {
      return array.reduce((users, user) => {
        Object.keys(user).forEach(key => {
          users[key+'s'] = Array.isArray(users[key+'s']) ? users[key+'s'].concat(user[key]) : [user[key]]
        })
        return users
      }, {})
    }
    
    console.log(
      changeData(array)
    )

    0 讨论(0)
  • 2021-01-23 09:28

    You can map into your array and assign dynamic properties like this obj[prop] = value

    var array = [
        [
            ['firstName', 'Nork'], ['lastName', 'James'], ['age', 22], ['position', 'writer']
        ],
        [
            ['firstName', 'James'], ['lastName', 'Rodel'], ['age', 25], ['position', 'programmer']
        ]
    ];
    
    var convertedArray = array.map(function(line){
       var obj = {};
       line.forEach(function(prop){
         obj[prop[0]]=prop[1];
       });
       return obj;
    });
    
    console.log(convertedArray);

    0 讨论(0)
提交回复
热议问题