Merge Array to Object Array JavaScript

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

提交回复
热议问题