Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
164
rated 0 times [  167] [ 3]  / answers: 1 / hits: 18141  / 6 Years ago, wed, november 14, 2018, 12:00:00

I have a fixed JSON array that contains 3 arrays. After the JSON has been fetched I am trying to merge them into one array. Here is what I have attempted but the Vue.JS array seems empty.



PREVIOUS



this.items = items;


NEW ATTEMPT



this.items = items.concat.apply([], arrays);


I have put an example of the 3 page demo at the link below:



https://arraydemo.netlify.com



<body>
<!-- Page List -->
<div class=container text-center mt-5 id=app>
<h1 class=display-4>Vue Page Output:</h1>
<!--<h2>{{items[0][0].page1}}</h2>-->
<h2>{{items.page1}}</h2>
</div>
<div class=container text-center mt-5>
<h3>Other Pages</h3>
<a href=products.html>Products</a>
<a href=contactus.html>Contact Us</a>
</div>
<!-- /.container -->

<script type=text/javascript>
const app = new Vue({
el: '#app',
data: {
items: []
},
created: function () {
fetch('test.json')
.then(resp => resp.json())
.then(items => {
this.items = items.concat.apply([], arrays);
})
}
});
</script>
</body>


JSON



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


DESIRED JSON OUTPUT



JSON



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

More From » arrays

 Answers
67

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)




[#53117] Thursday, November 8, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
loric

Total Points: 110
Total Questions: 96
Total Answers: 91

Location: Estonia
Member since Wed, Jun 8, 2022
2 Years ago
;