[Vuejs]-Merge arrays within an array using Javascript/Vue.Js

2πŸ‘

βœ…

you can iterate through each object where each object is an array, loop through the nested array and push the objects to a new array.

I hope this will solve your issue

var arr = [
    [
    {
        "page1": "Company Name"
    }
    ],
    [
    {
        "products": "Product List"
    }
    ],
    [
    {
        "contactus": "Contact Us at Acme Corp"
    }
    ]
]

// normal way
var mergedArrNormalWay = [];

arr.forEach(o => {
 o.forEach(so => mergedArrNormalWay.push(so))
})


// using concat

var merged = [].concat.apply([], arr);


console.log("merged in  a normal iteration way using for each", mergedArrNormalWay);

console.log("reduced way", merged)
πŸ‘€Learner

1πŸ‘

Given your JSON example above, and the desired output, calling .flat() on your outer array should work for you.

someArray.flat()

MSDN – Array.prototype.flat()

πŸ‘€chearmstrong

0πŸ‘

Your question isn’t clear whether you want to end up with an array of objects, or an array of arrays. I’ve assumed you want an array of arrays (as this is slightly more complex), but you could simplify the below (specifically the Object.entries) if you require an array of objects:

merged = [];

items.map(
  item => item.forEach(inner => (
    merged.push(Object.entries(inner).flat())
  ))
);
πŸ‘€trh88

Leave a comment