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

MySQL field being updated upon page unload

I'm currently developing a Content Management System (CMS) that allows users to access and organize records within a MySQL database. One of the features I have implemented is a user login system for the CMS. As part of this project, I am working on in ...

What is the best way to store the dom in cache to ensure that the page remains unchanged when navigating back using the back button?

When adding models to my JavaScript application's model collection using AJAX calls, I encounter an issue where if I click on a model and go to the next page, all the loaded models disappear when I hit the back button. What is the most effective way t ...

Utilize the onClick event to access a method from a parent component in React

Looking for guidance on accessing a parent component's method in React using a child component? While props can achieve this, I'm exploring the option of triggering it with an onClick event, which seems to be causing issues. Here's a simple ...

tips for incorporating async/await within a promise

I am looking to incorporate async/await within the promise.allSettled function in order to convert currency by fetching data from an API or database where the currency rates are stored. Specifically, I want to use await as shown here, but I am unsure abou ...

Display the element when the input is in focus

I'm currently working on optimizing a code snippet. The idea is to display a paragraph tag showing the characters remaining when you focus on a textarea. Here's what I have so far: import React, { Component } from "react"; class Idea extends Co ...

Encountering a JavaScript/TypeScript issue that reads "Unable to access property 'Items' as it is undefined"

I encountered an issue with Javascript where I'm receiving an error message stating "Cannot read property 'Items' of undefined". The this keyword is consistently showing as undefined in the Base class. How can this problem be resolved? Coul ...

The ZIP file downloaded from NodeJS is corrupted and cannot be opened

Currently, I am utilizing the following code to create a MySQL dump in memory, then zip that SQL file with a password from memory and save it to the hard drive so it can be streamed to the client... /* DUMP - database */ var mysqld ...

Changing the color of the timePicker clock in material-ui: a step-by-step guide

I have been attempting to update the color of the time clock in my timeInput component (material-ui-time-picker) for material-ui, but unfortunately, it is not reflecting the change. Here is the code I am using: <TimeInput style ={heure} ...

The element is implicitly classified as an 'any' type due to the index expression not being of type 'number'

Encountering a specific error, I am aware of what the code signifies but unsure about the correct interface format: An error is occurring due to an 'any' type being implicitly assigned as the index expression is not of type 'number'. ...

Transfer JSON data from a web URL straight into couchDB using cURL

Is there a way to directly insert JSON data obtained from a curl -X GET command into a couchDB database? For example, is it possible to achieve the following: >>> curl -X GET -H "some_header" http://some_web_JSON -X POST http://127.0.0.1:port/so ...

Troubleshooting the issue with ajax loadXml callback functionality

My table is empty and I can't figure out where the mistake is. I want to use the console to debug, but I'm not sure how. Update: I found a working sample here http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_xml2. I used similar code, bu ...

The element "name" could not be located in the JSONObject

Whenever attempting to retrieve a JSONObject from a JSONArray, an error is encountered: JSONObject["name"] not found. The code snippet that triggers this error is as follows: System.out.println(jsonArray); for (int k = 0; k < jsonArray.length(); k ...

What is the process for defining default prop data in Next.js?

Currently, I am in the process of developing a React/Next app with CRUD functionality. In regards to the update form, I have included the code below which is responsible for fetching existing data and updating it via an API. However, there seems to be a ma ...

Using AngularJS to calculate the right responses and show the overall score in a quiz

Can someone please provide guidance on how to iterate over questions in AngularJS for a quiz application and display the correct answers? I am new to programming and struggling with this. The quiz is structured in JSON format below: "questions": [{ ...

Why does my script seem to be missing from this GET request?

Encountering an issue while setting up a page using npm and grunt. Request URL:http://localhost:9997/bower_components/requirejs/require.js Request Method:GET Status Code:404 Not Found The problematic html code is as follows: <script> ...

What is the process for displaying data submitted through a form on page B to page A using Node and Express?

Dealing with the issue Hello everyone. I've been struggling for the past 30 minutes trying to figure out the rendering method problem I'm facing. Whenever I try to post data through a form from Page A and then render that data on Page B, I keep ...

After a loop, a TypeScript promise will be returned

I am facing a challenge in returning after all calls to an external service are completed. My current code processes through the for loop too quickly and returns prematurely. Using 'promise.all' is not an option here since I require values obtain ...

What is the best way to customize a component in a view?

<template> <div class="about"> <Header /> <h1>Welcome to the dashboard page</h1> </div> </template> <script> import Header from "../components/layout/Header.vue"; export default { name: "dashb ...

Utilize HTML, AJAX, and JavaScript to retrieve the location of the current user and display markers for other users on a

I am attempting to display on a single map the current location of a user and markers for other users, whose locations are obtained through an ajax post. In essence, I am looking to merge the concepts from: Google Maps Geolocation Example with: Multiple ...

Move the internal array pointer forward to the next record in order to apply the insertAfter function within the jquery code

As a new jQuery user, I'm attempting to develop a jQuery function using data provided by PHP. My goal is to arrange DIV elements in order of their values using insertAfter method. However, I seem to be encountering some difficulty in advancing the poi ...