Having two arrays of objects is quite common for me:
var parents = [
{ id: 77777, data: {}},
{ id: 88888, data: {}},
{ id: 99999, data: {}}
]
var children = [
{
belongTo: 77777,
data: [
{ id: 111, data: {}},
{ id: 222, data: {}}
]},
{
belongTo: 99999,
data: [
{ id: 333, data: {}}
]
}
]
My ultimate goal is to combine parents and children into one comprehensive array:
var all = [
{ id: 77777, data: {}},
{ id: 111, data: {}},
{ id: 222, data: {}},
{ id: 88888, data: {}},
{ id: 99999, data: {}},
{ id: 333, data: {}}
]
In my quest to achieve this merge efficiently, I have experimented with various methods. Unfortunately, splitting or merging them together and then flattening the result always seemed overly complicated.
I wonder, what could be the simplest way to accomplish this merge?
Here's a method I've attempted (which proved ineffective):
children.map(function(child) {
var parentIndex = parents.map(function(x) {return x.id}).indexOf(child.id)
parents.splice(parentIndex + 1, 0, child.data)
})
[].concat.apply([], parents)