When it comes to JavaScript arrays with multiple dimensions, objects are subject to replacement

I am experiencing an issue with a function that is supposed to assign an object inside a two-dimensional array. However, the assignment seems to be overwriting the previous object in the array.

var markersN = {};
var markersNArray = []

function addMarkerN(lat, lng, id, name, key) {
    markersN[key] = {};
    var newMark = new google.maps.Marker({
        /*marker properties*/
    });
    markersNArray.push(newMark);     //This successfully pushes every object to a one-dimensional array
    markersN[key][id] = newMark;     //However, this line replaces the previous object in the markersN[key] array
}

This is how I invoke the function:

for(var j=0; j<sekolah[i].nonlat.length; j++){
        addMarkerN(sekolah[i].nonlat[j], sekolah[i].nonlon[j], j, sekolah[i].nonname[j], sekolah[i].key);
    }

This is the desired structure of the array:

Array 
(
    [0] => Array
           (
               [0] => { /*marker object*/ }
               [1] => { /*marker object*/ }
           )
)

However, this is the actual resulting array structure:

Array 
(
    [0] => Array
           (
               [1] => { /*marker object*/ }
           )
)

I would like guidance on what I might be doing wrong and how I can prevent the function from overwriting the previous object in the array. Thank you.

Answer №1

Each time addMarker is called with a key that has been previously used, markersN[key] gets overwritten. To prevent this, make sure to check if an entry already exists for the specified key in makersN before initializing.

if (typeof markersN[key] === 'undefined') {
  markersN[key] = {};
}

Answer №2

One interesting thing about the addMarkerN function is that it sets markersN[key] = {}; each time it's called, resulting in the value of markersN[key] being an empty array.

Answer №3

get rid of the following line from within the function,

markersN[key] = {};

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

What is the correct way to transform an Error object to a string in Node.js?

Every time I input a duplicate entry in mysql, this error pops up. { [Error: ER_DUP_ENTRY: Duplicate entry '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="35465458455950755258545c591b-565a58">[email protected]< ...

javascript - modifying nested field based on condition in map

In the scenario of having an array like this: people = [ { name: 'Bob', sex: 'male', address:{ street: 'Elm Street', zip: '12893' } }, { name: ...

Tips for showcasing the latter portion of text within an HTML select dropdown menu

I have a select drop-down list with a fixed width of 80px, as shown in the image below: https://i.sstatic.net/pCpI9.png <select id="dd_country_code_2" name="dd_country_code_2" style="width: 120px; height: 23px;"> <option value="SEL">(Cou ...

Prevent inserting empty values into an array

My goal is to create a function that takes the students' ID, score, last name, and first name, compares them based on their score, last name, and then first name, and displays the result in descending order. To achieve this, I have utilized a Compara ...

Browsing through json subgroups

Having issues with filtering an array within my JSON file. Filtering the main array works fine, but I'm struggling to filter subarrays. This is the structure of my JSON file: [ { "id": 1354, "name": "name", "type": "simp ...

Strip all null entries from the URL string

I'm attempting to eliminate all empty parameters from a URL string. This is how my URL appears: http://localhost/wm/frontend/www/?test=&lol=1&boo=2 The desired output from my code should be: http://localhost/wm/frontend/www/?lol=1&boo=2 ...

When the response is manually terminated, the next middleware layer in express.js is invoked

I recently noticed an unusual occurrence: Even though I am explicitly ending the request using res.json() in one express middleware, the request still cascades down to the next middleware. It is important to mention that I am not utilizing next() anywhere ...

What is the best way to invoke a function with a variable number of arguments?

I am struggling with passing each element of an array as parameters to a function. For example: $myArray = array("element1","element2","element3"); //Pass each element as a new parameter to a function myFunction($element1, $element2, $element3); //If th ...

Query the number of Firebase instances using the firebase.appCount property in Firebase v

When setting up Firebase in my React applications, I typically initialize it as follows: if (firebase.apps.length < 1) { firebase.initializeApp(firebaseConfig); // Additional initialization for other Firebase products } This method was working flaw ...

Can someone provide guidance on organizing an array of objects by a specific property value using Powershell?

Let's say I have a variable that contains a line with several arrays: @{sourceDSAcn=B; LastSyncResult=0} @{sourceDSAcn=A; LastSyncResult=9} @{sourceDSAcn=C; LastSyncResult=0} @{sourceDSAcn=M; Last SyncResult=10} My goal is to sort this line alphabeti ...

Deploying NextJs application with Firebase's static site generation (SS

TL;DR The new data I add to my project is not displaying on the site, even though it's in the database. The issue arises after deploying with Firebase. I created a meetup website using Firebase as the backend. Everything works fine in development mo ...

How can you efficiently identify and resolve coding errors or typos in your code?

While practicing node.js and express.js, I encountered an issue with finding typos. One such instance was when I mistakenly typed: const decoded = jwt.veryfy(token, config.get('jwtSecret')); instead of jwt.verify. Even though I eventually disc ...

What could be preventing me from exporting and applying my custom JavaScript styles?

This is my primary class import React, { Component } from 'react'; import { withStyles } from '@material-ui/core/styles'; import styles from './FoodStyles'; class Food extends Component { render () { return ( & ...

Having trouble establishing a connection between Atlas and Node.js

Here is the content of my server.js file: const express = require('express'); const cors = require('cors'); const mongoose = require('mongoose'); require('dotenv').config(); const app = express(); const port = pro ...

Implement dynamic configuration injection by allowing users to specify the name of a configuration file during runtime, instead of having it fixed in the code

In my development using webpack, I am exploring ways to make my application configurations more dynamic. Presently, the project is a create-react-app that has been ejected. For instance, when creating a local build in my package.json file, I include the f ...

Tips for reusing multiple sequences of chained transitions in D3

Looking for a more efficient way to code two lengthy sequences of chained transitions with varying order, properties, and attributes. For example, one sequence might be a, b, c, d, e, f, g, h, and the other e, f, g, h, a, b, c, d. Tried the code below with ...

"Troubleshooting tip: encountering a SyntaxError message stating 'import declarations may only appear at top level of a module'? Here's

After downloading fetch-jsonp by running npm i fetch-jsonp and adding its dependency to my package.json, I attempted to import it using the following code at the top of my main.js: import fetchJsonp from 'fetch-jsonp'; However, I kept encounter ...

Progressive rendering of particles in THREE.js

I am new to the world of 3D and I'm trying to render particles as they are created. My goal is to have these 2000 particles render individually as they are created, but with the current code, they only render once all particles have been created. I h ...

Unable to access CKEditor information from PHP using MySQL database

I need assistance, my database is not being updated even though there are no errors. Can someone please help me with this? Below is the code for faqs.php: <div class="myeditor"> <form method="post" action="insert.php"> FAQs & ...

The footer is now accompanied by the <v-navigation-drawer> on the side

I am looking for a way to dynamically adjust the height value of a style applied to an element based on certain conditions. Specifically, when scrolling to the bottom, I want the height to be 77.5%, when the footer is not visible at all, it should be 100%, ...