Christian Curi
Christian Curi

Reputation: 3

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'
  }
]

Upvotes: 0

Views: 86

Answers (3)

Jack Bashford
Jack Bashford

Reputation: 44087

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);

Upvotes: 1

basic
basic

Reputation: 3408

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);

Upvotes: 0

junvar
junvar

Reputation: 11574

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)

Upvotes: 4

Related Questions