简体   繁体   中英

JavaScript convert Array of Array of Objects into Array of objects

I need convert Array of Array of Objects into a simple Array of objects using JavaScript

Below i go put the current code with the current output

const result = [
  [
    {
      name: '1'
    },
    {
      name: '2'
    }
  ],
  [
    {
      name: '3'
    },
    {
      name: '4'
    }
  ],
  [
    {
      name: '5'
    }
  ],
  [
    {
      name: '6'
    }
  ]
]

const a = result.map(item => {
  return Object.assign({}, ...item)
})


console.log(a)

Output of the above code (current and wrong output)

[ { "name": "2" }, { "name": "4" }, { "name": "5" }, { "name": "6" } ]

The expected and needed output

[
  {
    name: '1'
  },
  {
    name: '2'
  },
  {
    name: '3'
  },
  {
    name: '4'
  },
  {
    name: '5'
  },
  {
    name: '6'
  }
]

Looks like you're looking for flat ( mdn )

 const result = [ [ { name: '1' }, { name: '2' } ], [ { name: '3' }, { name: '4' } ], [ { name: '5' } ], [ { name: '6' } ] ] const a = result.flat(); console.log(a) 

There's a simple and well-supported way to flatten arrays without using flat - use reduce and push (not concat for efficiency).

 const result = [ [ { name: '1' }, { name: '2' } ], [ { name: '3' }, { name: '4' } ], [ { name: '5' } ], [ { name: '6' } ] ] const a = result.reduce((acc, curr) => (acc.push(...curr), acc)); console.log(a); 
 .as-console-wrapper { max-height: 100% !important; top: auto; } 

ES5 syntax:

 var result = [ [ { name: '1' }, { name: '2' } ], [ { name: '3' }, { name: '4' } ], [ { name: '5' } ], [ { name: '6' } ] ] var a = result.reduce(function(acc, curr) { return (Array.prototype.push.apply(acc, curr), acc); }); console.log(a); 

You could use Array.prototype.concat to merge the arrays.

Array.concat

 const result = [ [ { name: '1' }, { name: '2' } ], [ { name: '3' }, { name: '4' } ], [ { name: '5' } ], [ { name: '6' } ] ] const b = Array.prototype.concat.apply([], result); console.log(b); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM