Storing socket.io data in an array

Having trouble getting the desired array of arrays from my socket.io emitter. The structure I need is:

[ [{...},{...},{...}] , [{...},{...}] , [{...}] ]

But instead, I am receiving a different format.

https://i.stack.imgur.com/3PY0u.jpg

I require all the arrays to be in one master array for rendering bootstrap cards for each sub array.

Here is the client-side code snippet:

const socket = io("http://localhost:5000");

    socket.on('data', (dta) => {
        handleData(dta.data);  
    })

    function handleData(data) {
      const masterArray= [];
        masterArray.push(data);  
        console.log(masterArray);   
    }

And here's the server-side code:

for(let i = 0 ; i < alarmpanels.length ; i++) {
const ElkClient = elkClient.ElkClient;
    let client = new ElkClient({
        connection: {
          name: alarmpanels[i].name,
          host: alarmpanels[i].host,
          port: alarmpanels[i].port,
          secure: alarmpanels[i].secure,
          zones: alarmpanels[i].zones
     }
  });

  connectClient(client);
}

  async function connectClient(client) {
    await client.connect();
    const zonesArray = client.options.connection.zones;
    const arr = [];
      try {
        const clhost = client.options.connection.host;
        const clport = client.options.connection.port;
        const clsecure = client.options.connection.secure;
        let data = await client.getArmingStatus();
        for (i = 0 ; i < zonesArray.length ; i ++) {
        const armUpState = await data.areas[i].armUpState;
        const clName = client.options.connection.name;
        const zoneName = zonesArray[i].name;
        const siteName = zonesArray[i].site;
        const clzone = zonesArray[i].zone;
        const totalPanels = zonesArray[i].length;

        const info = new PanelStatus(clhost, clport ,clsecure, clzone, siteName, clName, zoneName, armUpState, totalPanels);
        arr.push(info);
        }


      io.on('connection', (socket, req) => {
          socket.emit('data', {data: arr});
        })

      }
      catch (err) {
        console.log("Connection Lost!");
      }

    }

Answer №1

To enhance your client code, consider making the following adjustments:
1) Declare the masterArray outside of the handleData function.
2) Utilize the spread operator (...) when pushing data to the masterArray.

const masterArray = [];

/*

const socket = io("http://localhost:5000");

socket.on("data", dta => {
  handleData(dta.data);
}); 

*/

function handleData(data) {
  masterArray.push(...data);
}

handleData([{ a: 4 }, { b: 5 }]);
handleData([{ z: 4 }]);
handleData([{ p: 4 }, { q: 5 }, { r: 5 }]);

console.log(masterArray);

Answer №2

If you are familiar with es2020, then you can easily utilize Array.flat()

let initialArray = [
  [{
    item1: 1,
    item2: 2,
    item3: 3
  }, {
    item4: 4,
    item5: 5,
    item6: 6
  }, {
    item7: 7,
    item8: 8,
    item9: 9
  }],
  [{
    item10: 10,
    item11: 11,
    item12: 12
  }, {
    item13: 13,
    item14: 14,
    item15: 15
  }],
  [{
    item16: 16,
    item17: 17,
    item18: 18
  }]
]

const flattenedArray = initialArray.flat()

console.log('initialArray', initialArray)
console.log('flattenedArray', flattenedArray)

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

Refresh the page once the function has been executed

Recently, I came across a basic javascript code that I need some help with. I want to reload the page after certain elements have faded out and back in. The problem is, I'm not sure where exactly I should include the window.location.reload(); function ...

To grab a specific CSS attribute from a stylesheet using JavaScript

I am looking for a way to extract the value from a CSS file using a JavaScript function. Take a look at my code snippet below: HTML file -> <link rel="stylesheet" type="text/css" href="test_css.css" /> <script type="text/javascript ...

Markers on Google Maps are failing to display when the locations are retrieved from a database

I am currently incorporating Google Maps API into my website using Node.js and mongodb. My Node.js express app fetches locations from mongodb, and I have successfully set up the map on my website. However, I am encountering an issue where only the hardcode ...

Managing simultaneous access to a variable in NodeJS: Best practices

For instance: var i = 0; while(true) http.request('a url', callback_f); function **callback_f**(){ **i++**; } In this straightforward scenario, multiple requests could unintentionally increase the value of i simultaneously. How can I creat ...

Personalize the drop area in Filepond

Is there a way to customize the filepond droparea by adding custom HTML with placeholder images to guide users on what kind of images should be uploaded and allow multiple uploads? I attempted to add placeholders in an absolutely positioned container, but ...

Encountering an issue of duplicate key error when using multiple v-for loops with various keys

I've encountered an issue while working on a Python application that utilizes Vue.js. A ticket came my way with an error message stating: [Vue warn]: Duplicate keys detected: ''. This may cause an update error. (found in Root) The pro ...

Utilizing PHP and Ajax to showcase individual row details within a while loop upon clicking a hyperlink

In the midst of a new project, I find myself faced with a task where the user can log in and view their personal delivery orders. The list of deliveries is generated using a while loop. However, whenever I click on the details button for an item in the lis ...

What could be causing my AJAX code to fail in retrieving information from an API?

Hey everyone, I'm new here and hoping to get some help with an issue I'm facing. I've written a code to fetch data from an API and display it on my HTML page, but for some reason the AJAX code isn't working. There's nothing showing ...

Verify whether a pop-up window has been opened

Situation: Greetings, I provide a sensitive service to my clients. However, some of them are generating advertisement popups (using JavaScript) on their websites where my service is integrated, causing issues for us. My service involves a .js file hosted ...

Trouble with serving CSS files using Express static directory

In my app.js file, I have the following code: app.use(express.static(path.join(__dirname, '../public'))); This code snippet is from my main layout page: <link rel="stylesheet" href="/css/styles.css"> Despite trying various combinations, ...

Is nested testing the key to an elegant JQuery/AJAX form validation solution?

As I implement form validation with JQuery/AJAX, my goal is to provide a seamless experience for users. When an entry is missing or incorrect, I aim to display a single alert message and return the user to the form so they can make adjustments and resubmit ...

Swapping out the JSON data from the API with HTML content within the Vue.js application

I am currently working on a project involving Vite+Vue.js where I need to import data from a headless-cms Wordpress using REST API and JSON. The goal is to display the titles and content of the posts, including images when they appear. However, I have enco ...

Can anyone suggest an effective method for displaying images using JavaScript by specifying a route and filename?

Currently, I have the following code snippet: const route = '/Images/Banner/'; const slides = [ { name: "banner-01", url: `${route}banner-01.png` }, { name: "banner-02", url: `${route}banner-02.pn ...

Is it possible to convert an object and/or a nested array with objects into a JSON string without relying on JSON.stringify?

Struggling to generate a correct JSON string from an object without relying on JSON.stringify(). Presenting my current implementation below - var my_json_encode = function(input) { if(typeof(input) === "string"){ return '"'+input+&apo ...

Transforming JavaScript Code into C# Syntax

I could really use some assistance. I've got a JavaScript code snippet here. var regiondb = new Object() regiondb["africa"] = [{value:"1", text:"Cairo"}, {value:"2", text:"Casablanka"}, {value:"3", text:"T ...

Encountering a Error 400 Bad Request when using gatsbyjs and expressjs for fetching

I created a backend using ExpressJS to send emails. The backend is deployed on Heroku and works well when tested with Postman. However, I encountered an issue with CORS when trying to access it from my Gatsby site running locally. Below is the ExpressJS c ...

PHP is failing to send a JSON response, but no errors are being logged in the PHP error log or displayed in the

Hey there, I'm feeling a bit frustrated and really not a fan of Javascript at all. Can someone please help me figure out why this isn't working? It's frustrating because everything seems fine when I return a simple string instead of trying t ...

Encountering a 404 error with Next.js 13 dynamic routing

Whenever I click on an item, it redirects to the dynamic route "http://localhost:3000/products/{id}" but instead of displaying the data, I get an error. Here is my file structure: app components Product.js pages Products [id].js layou ...

Removing all Null Form Inputs from the Document Object Model upon Submission utilizing JavaScript

I am currently working on a conditional Shopify form that was passed down to me from another developer. The form utilizes JavaScript/Jquery for field validation, ensuring that all mandatory fields are completed before proceeding to the next step. After mak ...

Inject various JavaScript data into different div containers

The issue at hand is quite straightforward. Here is a sample for displaying a single variable in a div with the "container" ID: let first = 5; document.getElementById('container').innerHTML = first; <div id="container"></div> How ...