0

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

3 Answers 3

4

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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

3 Comments

This is inefficient as concat would create a new array every time. A more efficient version would be to push elements to acc.
OK @slider I'll change that.
Fixed @slider, any better?
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.