Unleashing the Array within a JavaScript Object

Currently, I am successfully receiving messages from a Server via Websocket. The received messages are in the form of a Javascript Object, and my goal is to extract the necessary data from it and update the state of my React app accordingly.

Here is the code snippet I am currently using:

connection.onmessage = function (newMessage) {

        if(newMessage.data == '{"msg":"ping"}' ){
            connection.send('{"msg": "pong"}')
        }

        newMessage = JSON.parse(newMessage.data)
        console.log(newMessage.fields)       
    }

After receiving the message, I am logging the 'fields' property of the parsed object.

To see the actual object that I am working with, you can visit this Javascript Object.

Specifically, I am interested in the Array located at args/0. How can I extract this array from the object?

Thank you for your help.

Answer №1

It might not be the best approach to modify newMessage within your connection.onmessage function. Adding more logging when receiving a new message could also be beneficial. Have you considered giving this version a try?

connection.onmessage = function (newMessage) {
    console.log("Received new message :", newMessage.data);

    if(newMessage.data == '{"msg":"ping"}' ){
        connection.send('{"msg": "pong"}')
    }

    var parsedMessage = JSON.parse(newMessage.data);

    if (parsedMessage.msg === "changed") {
        console.log("Received changed message :", parsedMessage.fields.args); 
    }
}

I hope this suggestion proves helpful!

Answer №2

To retrieve the 'args' information from the JSON object, you can simply use 'newMessage.args'

var newMessage = {eventName: 'aname', args: ['data1','data2'] }
document.getElementById('output').innerHTML = newMessage.args
<div id='output'></div>

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

Using the spread operator in React to distribute JSX elements within a map function

I am struggling with mapping over an array within another array to create a Picker and am having difficulty returning JSX elements instead of an array of JSX elements. Here is the code example: {modelA.map((mA) => { const pickerItems = mA.modelB.m ...

Updating item information within an array in Vue.js

I'm currently working on integrating an edit feature into a task application using Vue JS. My issue lies in the fact that I have a click event assigned to the edit button - @click="editShow" which displays input fields for editing all items instead ...

using app.use to directly pass arguments without delay (NODE.JS)

I'm currently figuring out why the code 1 is functioning properly, while the code 2 is not... app.js: // Implementing Routes var server = require('./routes/server'); app.use('/', server); Route.js: var express = require(&a ...

Find the difference between the sum of diagonals in a 2D matrix using JavaScript

I'm currently practicing on hackerrank and came across a challenge involving a two-dimensional matrix. Unfortunately, I encountered an error in my code implementation. 11 2 4 4 5 6 10 8 -12 The task at hand is to calculate the sum along the primary ...

Using JavaScript functions on HTML data loaded by the jQuery.append() method: A guide

Utilizing JSON data, I have successfully generated HTML content representing Questions and Multiple Choice Questions. My next goal is to capture user responses in an array after the submit button is clicked. This involves storing which radio button the use ...

The useEffect() method used without any cleanup function

It is mentioned that, "Every time our component renders, the effect is triggered, resulting in another event listener being added. With repeated clicks and re-renders, numerous event listeners are attached to the DOM! It is crucial to clean up after oursel ...

Failure to receive results from $.getJSON request

I am currently working on developing a web page that allows users to search and retrieve Wikipedia pages based on their search results. Below is the relevant HTML code for the search feature: <form class='search-form' onsubmit='return f ...

Retrieve the data-src attribute from the lightGallery plugin

I have integrated the lightgallery plugin into my website from Currently, I am struggling to retrieve the data-src value when an image is clicked. The basic HTML structure is as shown below: <div id="work-grid" class="grid wow fadeIn animated"> ...

Tips for creating a unique custom UI headline using ReactJS, CSS, and bootstrap

Looking to create a design that is responsive in ReactJS using Bootstrap or CSS if needed. I need assistance with placing separators between columns and ensuring the values of each label are aligned in the same column but on the next line. The layout shoul ...

Arranging JSON based on values in an array using node.js

Seeking assistance with sorting a JSON object by specific keys within a node.js program. The task involves arranging the object in ascending order based on the "trip_miles" value when the "trip_name" equals CC, and then extracting only the id's as out ...

Persistent change issue with JQuery CSS function

Looking for some help with a button-bar div that I want to display only after the user clicks on a "settings" button. Currently, I have set the button-bar div to have a display:none property in my css file. However, when the settings button is clicked, t ...

There seems to be a limitation in JS/JQuery where it is unable to append HTML that spans

I am encountering an issue with retrieving data in a div element. It seems that the function provided does not work correctly for files larger than a single line of code or even possibly a string. What can be done to resolve this? <ul class="dropdo ...

execute function following ng-repeat

I'm diving into Angular for the first time and I want to start with a simple example. After using ng-repeat to display some data, I'd like to manipulate that data with JavaScript functions. However, I'm not sure when to trigger the JavaScri ...

Dropdown menu featuring a customizable input field

Is it possible to have a drop-down list with an input textbox field for creating new items in the same dropdown menu? ...

Reorganize code in JavaScript and TypeScript files using VSCode

Is there a way to efficiently organize the code within a .js / .ts file using Vscode? Specifically, when working inside a Class, my goal is to have static variables at the top, followed by variables, then methods, and so on automatically. I did some resea ...

How to use jQuery Animate to create a step-by-step animation with image sprites?

I'm working on creating an image sprite using jQuery and I'm curious if it's feasible to animate it in steps rather than a linear motion. I initially tried using CSS3 animations, but since IE9 is a requirement, the animations didn't wor ...

Model with no collection involved

Take a look at this Model and View setup. Why is the indicated line not functioning as expected? var app = app || {}; (function () { app.CurrentUserView = Backbone.View.extend({ el: $('.avatar-container'), template: ux.templ ...

Best resolutions and formats for Nativescript-Vue application icons

I'm a newbie when it comes to Nativescript, and I'm looking to change the icon for my app. After doing some research, I found this command: tns resources generate splashes <path to image> [--background <color>] This command seems li ...

Activate a dropdown menu following the selection of a date on a calendar input using vue.js

What I need to do is have two select fields, one for 'days' and the other for 'hours'. When a day is selected, the user should then be able to choose between two available time slots. If they choose day two, the available time slots sh ...

Emphasize sections of text within a chart

Looking for a Specific Solution: I've encountered similar problems before, but this one has a unique twist. What I'm trying to achieve is to search for a substring within a table, highlight that substring, and hide all other rows (tr's) th ...