Learn the step-by-step process of dynamically adding elements to a JavaScript object in JSON structure

We are attempting to dynamically generate a JSON object using a for loop. The intended result should resemble the following:

posJSON = [ 
    {
        "position": [msg[0].Longitude, msg[0].Latitude],
        "radius": 0.05,
        "color": [255, 255, 0, 255]
    },
    {
        "position": [msg[1].Longitude, msg[1].Latitude],
        "radius": 0.05,
        "color": [255, 0, 0, 255]
    }
]

When we manually create the object with the provided code above, everything works as expected. However, when we try to dynamically generate the object like this:

for(i=0; i < Object.keys(msg).length; i++) {
    posJSON.push({
        "position": [msg[i].Longitude, msg[i].Latitude],
        "radius": 0.05,
        "color": [255, 255, 0, 255]
    });
}

it does not function correctly. There seems to be an issue with the syntax, but we are having trouble pinpointing the error. Any assistance in resolving this matter would be greatly appreciated.

Below is the complete code snippet of the function:

import React, {Component} from 'react';
import DeckGL, {PathLayer} from 'deck.gl';
import DeckGL, {ScatterplotLayer} from 'deck.gl';
import $ from 'jquery'; 

var tableJSONStringed = null;
var posJSON = [];

//Position tracker

window.setInterval(function(){
    var request = $.ajax({
        url: "https://nedo93.000webhostapp.com/phpgetcoords.php",                 
        method: "POST",               
        dataType: "json"    
    });
    request.done(function( msg ) {              
        tableJSONStringed = JSON.stringify(msg, null, " ");
        var count = Object.keys(msg).length;            

        //CYCLE
        for(i=0; i < Object.keys(msg).length; i++) {
         posJSON.push({
        "position": [msg[i].Longitude, msg[i].Latitude],
        "radius": 0.05,
        "color": [255, 255, 0, 255]
    });

    });              
    request.fail(function( jqXHR, textStatus ) {
        //alert( "Request failed: " + textStatus );
    });
}, 5000);

export default class DeckGLOverlay extends Component {  

  static get defaultViewport() {
return {
  longitude: 11.25,
  latitude: 43.77,
  zoom: 16,
  maxZoom: 18,
  pitch: 40, //viewport tilt
  bearing: 0
};
  }

  _initialize(gl) {
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
}

 //Add in const { }, new layers's ID
  render() {
const {viewport, scatters, pos, icon, paths, trailLength, time} = this.props;   

//Add another instance of a new layer here:

const layers = [      
  new ScatterplotLayer({
    id: 'scatters',
    data: scatters,     
    radiusScale: 100,
    outline: false
   }),
  new ScatterplotLayer({
    id: 'pos',
    data: posJSON,      
    radiusScale: 100,
    outline: false
   }),    
   new PathLayer({
    id: 'paths',
    data: paths,        
    rounded: true,
    getColor: paths => [255, 0, 0, 255],
    getWidth: paths => 0.03,
    widthScale: 100
  })
];  

return (
  <DeckGL {...viewport} layers={layers} onWebGLInitialized={this._initialize} />
);      
  }    
}

For reference, the console output while running the for loop can be viewed here.

Answer №1

var posJSON = [];
var msg = [
    {Longitude: 1, Latitude:11, radius: 0.01, color: [221,2,32,1]},
    {Longitude: 2, Latitude:21, radius: 0.11, color: [321,2,23,1]},
    {Longitude: 3, Latitude:31, radius: 0.41, color: [521,2,22,1]},
    {Longitude: 4, Latitude:41, radius: 0.11, color: [121,2,02,1]},
    {Longitude: 5, Latitude:51, radius: 0.32, color: [253,2,22,1]},
]
msg.forEach(function(obj) {
    posJSON.push({
        "position": [obj.Longitude, obj.Latitude],
        "radius": obj.radius,
        "color": obj.color
    });
});

console.log(posJSON);

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

How can I prevent a repetitive div from appearing in a JQuery show/hide function?

Whenever I trigger my AJAX function, the loading image keeps repeating every time I click on the next page. I want to prevent this repetitive loading image and only display it once when I go to the next page. To address this issue, I created a <div cla ...

We encountered a problem while trying to create the route "/": Minification of HTML failed in Nuxt js

After successfully developing a Nuxt app that runs perfectly with "npm run dev," I encountered an error when generating the site using "npx nuxt generate." Despite my efforts, I cannot locate the source of the error. Any assistance would be greatly appre ...

Explore the world of textures transferring from Maya to Three.js

I'm looking to convert a Maya model to JavaScript for a simple model with textures. The conversion works fine, but the textures are not showing up. Here is my code: var loader = new THREE.JSONLoader(); loader.load( "models/t2.js", function(geometry) ...

Converting a Dictionary to JSON for Multipart/Form-Data in Swift

I am currently working on a Swift app that sends requests to servers containing both normal values and images. To achieve this, I am using a multipart/form-data request. The challenge I am facing is how to insert the JSON converted versions of arrays and d ...

Creating a hover effect for displaying image masks

My website features a profile page displaying the user's photo. I am attempting to create a functionality where when the user hovers over their photo, a transparent mask with text appears allowing them to update their profile picture via a modal. How ...

Enhancing Javascript Dialog Box with a Touch of Animation

Collaborating with the incredibly talented Mark Eirich has been an amazing experience. We have been working on revamping a JavaScript dialog box together, and Mark has set up something on JSFiddle that will be incredibly beneficial. However, I am seeking a ...

Proper method for verifying line-clamp in a Vue component

I came across a question that aligns perfectly with my current task - determining if text is truncated or not. The query can be found here: How can I check whether line-clamp is enabled?. It seems like my approach may not be accurate, so any guidance on ho ...

Preventing the reoccurrence of function events

I need to create an event triggered by a mouse click when the user clicks a button. The code snippet below shows my attempt, but I'm facing an issue where the function continues to run if the user clicks on a second input field after the initial one: ...

AngularJS not refreshing the view

I'm having an issue in my app where I calculate the total bill and display it on my view. The first time, everything works fine. However, when I increment the $scope.bill_total, the view is not updating even though I can see the change in the console. ...

Tips for moving and filling data in a different component using NextJS

Currently, I am developing an application using Next.js and tailwindcss. The Issue In essence, I have a table consisting of 4 columns where each row contains data in 3 columns and the last column includes an "Update" button. The data in each row is genera ...

Tips on customizing the appearance of two Material-UI Sliders across separate components

Looking to customize two sliders, each within their own react component. Slider in the first component const customizedThemeSlider1 = createTheme({ overrides:{ MuiSlider: { thumb:{ color: "#4442a9", marg ...

Revise the validation process for the drop-down menu and input field

Looking for help with text field validation based on a dropdown selection. There are two scenarios to consider: 1. User changes dropdown value and then enters text in the field. 2. User enters text in field and then changes dropdown. I've written cod ...

Using Switch Case and If Statements in Javascript and Jquery

Can you help me troubleshoot this code? It's designed to detect clicks and keypress events within the #ts_container div for buttons and anchors. The goal is to use an If statement in each case to determine if it's a click or keypress, then update ...

Parsing JSON without requiring the content-type header provided

Currently, I am in the process of switching from an old API to a new Express API. The issue I am facing is that the previous API did not need the content-type header for JSON data, however, Express requires it in order to properly parse the body into JSON. ...

Trouble with AJAX not properly fetching PHP JSON response

I recently encountered an issue with my jQuery AJAX request that sends user input to a PHP file. Initially, the code worked perfectly fine but adding "dataType: 'json'" caused it to malfunction. Here's how I set it up: $.ajax({ url: url ...

Error: global not declared in the context of web3

I've been attempting to integrate Web3 into my Ionic v4 project for some time now. However, I keep encountering errors when I try to serve the project. Specifically, I receive an error message stating that Reference Error: global is not defined. Cre ...

Disabling caching in bootstrap tabs for loading ajax content

My goal is to make bootstrap tabs load content through ajax queries. While this process is straightforward with Jquery tabs, which default to loading content via ajax query, it seems to be a different case for bootstrap. As such, I have come across the fo ...

Creating a webpage header with Javascript to mimic an existing design

I am in the process of building a website with 5 different pages, but I want the header to remain consistent across all pages. To achieve this, I plan to use an external JavaScript file (.js). The header includes the website name (displayed as an image) an ...

Utilizing Gson to efficiently parse each JSON object within a JSON Array when using Retrofit

I have a json response returning an array of results with objects, and I want to extract the fields from each object using my customObjectResponse class. The issue is that it expects an object, so I'm unsure how to modify the class to handle an array ...

jQuery Counter Effect encountering isNaN error when trying to display a number retrieved from a get API object

I am looking to display the numerical data retrieved from an API using JSON. I want to incorporate a counter effect that displays "isNaN" if necessary. The API URL returns an object with the total number saved in data.data. Can anyone assist me with achi ...