Combining arrays in a nested array with the help of Javascript/Vue.Js

I am faced with a JSON array containing 3 arrays that I need to merge into one array after fetching the JSON data. Although I attempted to do so using Vue.JS, the resulting array appears to be empty.

MY FIRST ATTEMPT

this.items = items;

MY LATEST ATTEMPT

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

I have provided a 3-page demo example in the link below:

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

EXPECTED JSON OUTPUT

JSON

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

Answer №1

Take each object in an array, loop through the nested arrays, and add the objects to a new array.

Hopefully, this solution resolves your problem.

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

// Normal way
var mergedArrNormalWay = [];

arr.forEach(obj => {
    obj.forEach(subObj => mergedArrNormalWay.push(subObj))
})

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

console.log("Merged in a normal iteration way using forEach:", mergedArrNormalWay);

console.log("Reduced way:", merged)

Answer №2

If you have a JSON example similar to the one above and you want the desired output, you can simply use the .flat() method on the outer array.

Simply call someArray.flat()

Here is a helpful resource on MSDN - Array.prototype.flat()

Answer №3

It seems like the question is a bit ambiguous regarding whether the desired outcome is an array of objects or an array of arrays. Assuming that an array of arrays is preferred for its complexity, the code snippet provided below utilizes Object.entries to achieve this. However, if an array of objects is required, the code can be simplified:

merged = [];

items.map(
  item => item.forEach(inner => (
    merged.push(Object.entries(inner).flat())
  ))
);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtaining the id in JavaScript from PHP to display information

This is the code I've written: <textarea id="summernote<?php echo $u->id ?>" name="isi" placeholder="Write here" style="width: 100%; height: 100px !important; font-size: 14px; line-height: 18px; border: ...

THREE.JS: Organizing Objects into Multiple Groups

Currently, I am in the process of learning THREE.js and attempting to create a playable Rubik's cube. My goal is to rotate a face as a whole instead of manipulating each cube individually. I have tried placing the cubes within a THREE.Group, but the ...

Creating unique random numbers using elements from my array without repeating

Hey there, I'm a beginner in C# and currently working on an application involving arrays. I've created an array with the following numbers: int[] array2 = new int[] { 1, 3, 5, 7, 9 }; My goal is to reorder these numbers in the array without any ...

Why does the fillText() method in HTML5 Canvas erase everything after using the clearRect() method?

Whenever I use the writeTextToCanvas method before the clearCanvas method, everything works perfectly. However, if I call the clearCanvas method first and then writeTextToCanvas, the drawing functions work fine after clearing the canvas but the fillText fu ...

Enhancing Your Vue Experience: A Guide to Highlighting and Selecting HTML Elements on Mouse Hover

Incorporating a navigation header using Vue, I utilize v-html to display it seamlessly. Check out the demo - here <section class="text-gray-700 font-heading font-medium relative bg-gray-50 bg-opacity-50"> <nav class="flex justify ...

If the condition is false, the Bootstrap 4 carousel will not transition to another slide

With Bootstrap 4, each slide contains a form section and there is a next button. I want to ensure that the carousel does not move to the next slide unless a certain variable is true (for form validation purposes). I have attempted using the onclick event ...

React Native displaying identical path

Is there a way to dynamically change routes in React Native when a button is pressed? Inside my SplashContainer component, I have the following method: handleToSignUp = () => { console.log("Running handleToSignUp") this.props.navigator.push({ ...

$.ajax causing a JSON input string malfunction

My web API requires the following JSON format for input: [{ "atrSpaUserId": "47fe8af8-0435-401e-9ac2-1586c8d169fe", "atrSpaClassLegendId": "00D18EECC47E7DF44200011302", "atrSpaCityDistrictId": "144d0d78-c8eb-48a7-9afb-fceddd55622c"}, { "atrSpaUserId": "47 ...

Implementing a smooth transition effect on an ajax tab

I have a tab code that uses ajax data attributes to load content. The tabs are loaded with ajax from PHP code based on the data attribute. How can I add a fade in/out effect to the tabs' content? I've attempted it but haven't been successful ...

Utilize Vue Slot with variable names for dynamic integration

My current dilemma involves a unique component called TableContainer, featuring dynamically named slots. // ... <td class="..."> <slot :name="'statuses-' + item.id" /> </td> <td class=""> ...

what is the method for retrieving JavaScript variables within a PHP script?

Is there a way to store a JavaScript variable value, such as var a, within a PHP script variable without relying on the post/get method or Ajax? <script> var count=3; $("#add_driver").click(function () { $( "#add_driver_section").replaceWit ...

Guide on Sending a POST Request via HTTPS in Websites

I am developing a browser extension for Chrome that requires sending a post request to a server using standard HTTP. However, this is causing a mixed content error when I'm on a website that uses HTTPS, and the browser refuses to process my request. ...

Adjust the sizing of all fonts following the switch in font styles

Seeking help for adjusting font-size across a responsive web page design using different font families. font-family:Cambria, "Hoefler Text", "Liberation Serif", Times, "Times New Roman", serif; To achieve responsiveness, various media queries were applie ...

delivering the optimized main RequireJS file as a static asset through NGINX servers

Is it true that serving static assets from NGINX or another server is better than using your Node.js application server? In my case, I have a single-page application where in production mode, only one optimized .js file is served from the index page, and ...

Alter the color of the dropdown background when it is changed

Currently, I am utilizing the Semantic UI React CSS library and find myself in need of changing the background color of dropdowns once an option is selected. https://i.sstatic.net/yZBK7.png to https://i.sstatic.net/LxTtT.png <Dropdown placeholder=&apo ...

Combining numerous data tables in Vue.js directly from JSON information through a single template

I need to develop a single vue template to display over 40 datatables with different table definitions passed in through an API. I am facing a challenge in dynamically pulling in the table data using key names defined in the table settings. I attempted t ...

In order to ensure accuracy, the 'to' date must always be after the '

By default, when selecting a start date, the end date should be displayed as greater than the start date. However, in my current code, if I select the start date, the end date is set to be the same as the start date. Below is my code snippet. Thank you in ...

Numerous Switches Similar to Tabs Using JavaScript and CSS

I'm looking to create tabs that operate as toggles, but with the twist that only one toggle can be active at any given time. Additionally, I need the tab content to appear above the actual tabs themselves. The challenge lies in the fact that I am usin ...

Ways to separate a portion of the information from an AJAX Success response

I am currently working on a PHP code snippet that retrieves data from a database as follows: <?php include './database_connect.php'; $ppid=$_POST['selectPatientID']; $query="SELECT * FROM patient WHERE p_Id='$ppid'"; $r ...

Failure to display div upon onmouseover event

The div 'hidden-table' is causing issues as it does not display even though the style attribute 'display:none' has been removed. I have attempted to show the table separately outside of the echo statement, and it appears to work correct ...