Browsing a Collection of Objects within an Array in JavaScript

After making an ajax request to load a JSON file and parsing it to store a reference to the object, I encountered issues while trying to loop through the object due to its structure.

Below is a snippet of the JSON data that I am working with:

{
  "markers": {
    "marker": [
      {
        "name": "john",
        "latitude": "53.4682282",
        "longitude": "-2.238547"
      },
      {
        "name": "david",
        "latitude": "53.4663409",
        "longitude": "-2.2328164"
      },
      {
        "name": "mathew",
        "latitude": "53.4668135",
        "longitude": "-2.2310998"
      }
    ]
  }
}

Despite attempting the following JavaScript loop, I have been unable to execute it successfully. (Note: the object derived from parsing the JSON is named markers.)

markers.forEach(function(marker) {
  console.log(marker.name);
});

Answer №1

markers is a container holding the array marker. It is necessary to loop through each marker

var obj = {
  "markers": {
    "marker": [{
        "name": "john",
        "latitude": "53.4682282",
        "longitude": "-2.238547"
      },
      {
        "name": "david",
        "latitude": "53.4663409",
        "longitude": "-2.2328164"
      },
      {
        "name": "mathew",
        "latitude": "53.4668135",
        "longitude": "-2.2310998"
      }
    ]
  }
}

obj.markers.marker.forEach(m => console.log(m.name));

Answer №2

Give this a shot:

markers.marker.forEach((marker) => {
  console.log(marker.name);
});

Answer №3

To retrieve the nested object, I had to access the inner object like this:

markers.markers.marker.forEach(function(marker) {
    console.log(marker.name);
});

Answer №4

Give this a shot:

'markers.marker.map((ma) => { console.log(ma.name); });`

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

Can a complete form be encapsulated within a single AngularJS directive?

While I have come across several instances of individuals utilizing a blend of HTML and directives to craft an AngularJS form (as seen here), my goal is to develop a self-contained widget. This widget would encompass all the necessary HTML for the form w ...

Leveraging Axios for form data submission

Is it possible to serialize data from an HTML form element and then post the data using a Post request with Axios? Below is the event code triggered when a button click occurs to submit the post: function form_submission(e) { var data = document.getEleme ...

Convert this JavaScript function into a jQuery function

I currently have this JavaScript function: function removeStyle(parent){ var rmStyle = document.getElementById(parent).getElementsByTagName("a"); for (i=0; i<rmStyle.length; i++){ rmStyle[i].className = ""; } } Since I am now using ...

Error in THREE.js: Failed to retrieve object at http://192.168.8.104:8080/[object%20Object] (Error code: 404) - Module: three.module.js

During my attempt to create a text loader in THREE.js, I encountered an error instead of getting the expected text output. three.module.js:38595 GET http://192.168.8.104:8080/[object%20Object] 404 (Not Found) I made various efforts to resolve this error ...

Ways to verify if the scroll bar of a user is not visible

Is there a method to detect if the user has forcibly hidden the scroll bar in the operating system? 1. Automatically based on mouse or trackpad 2. Always 3. When scrolling I want to adjust the width of an HTML element if the scroll bar is visible, which c ...

User update function is not being triggered by Ionic 2 Express call

I am currently working on implementing a feature in my Ionic 2 program that updates a user field when triggered. The code snippet below is from my user-service.ts file: // Update a user update(user: User): Observable<User> { let url = `${this.u ...

Node js process.kill(pid) is ineffective in terminating a Linux process

Trying to terminate background processes using nodejs process.kill(pid, 'SIGTERM') results in the processes not being killed. After running the node script provided below, I checked the processes using ps -efww | grep 19783 | grep -v grep in the ...

Using the jQuery $.each method with $.getJSON and struggling to access data within a nested array

I've been trying to achieve the same functionality in my jQuery code as my PHP code below, but so far I haven't been able to find any helpful information after nearly two days of searching. <script> $(document).ready(function(){ var s ...

Struggling to set the value for a variable within an Angular factory?

When dealing with a variable as an array, I have no trouble pushing objects inside and retrieving the values within the controller. However, when trying to directly assign an object to that variable, I run into issues. If anyone can assist me in achieving ...

Activate radio button exclusively for admin user

My current application includes an admin panel with functions to manage users. I use a while loop in the form creation to display 3 user types: Admin, Manager, and User, which are pulled from a database. Admin Manager User This is how my HTML Form look ...

Instructions on generating a fresh Ethereum or Solidity contract for every test using JavaScript and Truffle

overview After developing an Ethereum smart contract using the Solidity language, I utilized Ganache to deploy my contract for testing purposes. However, in order to conduct tests effectively, I need to create a new instance of my contract using JavaScrip ...

Image displaying recreation of drop down lists similar to those found on Facebook pop-up windows

Seeking guidance on how to create popup drop-down lists similar to Facebook's "Who liked this link?" feature. I believe it involves the use of jQuery. Click here for an example image. Any suggestions, folks? ...

Encountered a JSON parsing error when trying to import data into MongoDB

I've encountered an issue while attempting to import a json file into MongoDB using Java drivers. The error message I received is as follows: Exception in thread "main" com.mongodb.util.JSONParseException: at com.mongodb.util.JSONParser.read ...

Can you provide some insight into why the init() method is throwing an error?

My project utilizes DynamoDB access through https://www.npmjs.com/package/react-native-dynamodb. I followed the code provided on the website for implementation. The issue I'm facing is that when hovering over my .init() method in WebStorm IDE, it sho ...

Converting numerical elements in an array to strings

Looking for assistance with reformatting the values in this Array : [{abcd:1, cdef:7},{abcd:2, cdef:8}, {abcd:3, cdef:9}] I want to convert all the values into strings like so : [{abcd:"1", cdef:"7"},{abcd:"2", cdef:"8"}, {abcd:"3", cdef:"9"}] Can anyo ...

The importance of variables in Express Routing

I'm really diving into the intricacies of Express.js routing concepts. Here's an example that I've been pondering over: const routes = require('./routes'); const user = require('./routes/user'); const app = express(); a ...

How to eliminate duplicate items in an array and organize them in JavaScript

I am looking to eliminate any duplicate items within an array and organize them based on their frequency of occurrence, from most to least. ["57358e5dbd2f8b960aecfa8c", "573163a52abda310151e5791", "573163a52abda310151e5791", "573163a52abda310151e5791", "5 ...

Recursive method to determine if there are shared numbers between two arrays

Here is the challenge: create a recursive function that takes two arrays of positive integers and their sizes as parameters. The function should return 0 if there is at least one common element between the arrays, and 1 if there isn't. int findDisjoi ...

Evolution of JSON Schema or organization of JSON Schema data

We are facing a challenge with a large quantity of JSON objects that follow a JSON Schema. The problem lies in the fact that the JSON Schema is continually evolving, resulting in frequent changes to the schema such as adding or removing fields. This rende ...

Incorporate Current and Total Slide Counters into Your Bootstrap 5 Carousel

How can I incorporate slide numbering into this Bootstrap 5 carousel example? I want to display the current slide number and the total number of slides in the carousel. The slide counters can be found in the carousel-pager div, where pager-current repres ...