Skip to content

How to merge an array of array of objects into a single array?

In this quick post, you will learn how to merge / flatten an array of array of objects into a single array of objects in JavaScript. JavaScript provides an easy way to flatten array using the concat() method.

Let’s assume we have an array of objects inside another array.

let arr = 
[

	[{
			"day": "Monday",
			"spent": "4.5$",
			"remaining": "5.5$"
		},
		{
			"day": "Tuesday",
			"spent": "7.5$",
			"remaining": "2.5$"
		}
	],
	[{
			"day": "Wednesday",
			"spent": "1.0$",
			"remaining": "9.0$"
		},
		{
			"day": "Thursday",
			"spent": "7.0$",
			"remaining": "3.0$"
		}
	]
]

To merge / flatten this array of arrays we can use concat() method and merge them.

var result = [].concat.apply([],Object.values(arr);
console.log(result)
[

	{
		"day": "Monday",
		"spent": "4.5$",
		"remaining": "5.5$"
	},
	{
		"day": "Tuesday",
		"spent": "7.5$",
		"remaining": "2.5$"
	},
	{
		"day": "Wednesday",
		"spent": "1.0$",
		"remaining": "9.0$"
	},
	{
		"day": "Thursday",
		"spent": "7.0$",
		"remaining": "3.0$"
	}

]
See also  Show good morning, good night depending on the time in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.