Navigating through an array of objects in JavaScript

I've been struggling to extract data from an array of objects using pure javascript, but I'm just not seeing the results.

Issue Resolved!

A big shoutout for the invaluable personal assistance! Turns out, the array was being passed as a string and required parsing before iteration. Problem solved!

// Here is a sample of the array received by the function, which is not declared in this 
// JS file but rather received as a parameter. I'm including it so you can see the format
// of the data received
[{
    "id": 171659,
    "latitude": "-51.195946",
    "longitude": "-30.021810",
    "estado": "INSTALLED"
  },
  {
    "id": 171658,
    "latitude": "-51.196155",
    "longitude": "-30.021615",
    "estado": "INSTALLED"
  }
]

// My js file contains only the function that receives the data, shown below is the 
// entire file. The array itself is not declared here; it's simply received by the function.
// Data is successfully received but having trouble iterating through

// ====== Get Array ======
function getArray(data) {
  
  var json = JSON.parse(data); //The data comes in as a string, requiring parse()

  for (var i = 0; i < json.length; i++) { // Issue: values are undefined
  console.log(json[i].id);
  }
  
}   

Answer №1

You forgot to declare the data array

var data = [{
    "id": 171659,
    "latitude": "-51.195946",
    "longitude": "-30.021810",
    "estado": "INSTALADO"
  },
  {
    "id": 171658,
    "latitude": "-51.196155",
    "longitude": "-30.021615",
    "estado": "INSTALADO"
  }
]

for (var i = 0; i < data.length; i++) {
  console.log(data[i].id);

}

Updated response utilizing parameter.

//The provided array
var pass = [{
"id": 171659,
"latitude": "-51.195946",
"longitude": "-30.021810",
"estado": "INSTALADO"
  },
  {
"id": 171658,
"latitude": "-51.196155",
"longitude": "-30.021615",
"estado": "INSTALADO"
  }
]

getArray(pass);

//My function receiving date
function getArray(data){

  for (var i = 0; i < data.length; i++) {
   console.log(data[i].id);

  }
}

Answer №2

const locations = [
 {
   "id": 171659,
   "latitude": "-51.195946",
   "longitude": "-30.021810",
   "estado": "INSTALLED"
 },
  {
    "id": 171658,
    "latitude": "-51.196155",
    "longitude": "-30.021615",
    "estado": "INSTALLED"
  }
]
function displayLocations(locations){
  for (let i = 0; i < locations.length; i++) {
    console.log(locations[i].id);
}}

displayLocations(locations)

Make sure to assign your object to a variable before calling it in your function.

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

The scrolling behavior varies in Firefox when using the mouse wheel

Currently, I am working on a website where I want to display large text on the screen and have the ability to scroll two divs simultaneously. This functionality is already in place. I can scroll the divs, but I'm facing an issue with the jumps being t ...

Understanding the difference between Parameters in Javascript and Java

Currently, I am facing an issue where I am losing some information while sending an ajax request to a servlet. The specific parameter that I am losing data from is the "comment" parameter. Below are the last 4 lines of my ajax code: var params = "name=" + ...

Switching iFrame based on dropdown selection

Hello, I'm a beginner in the world of programming and I'm currently experimenting with creating a webpage. However, I've encountered a roadblock and could use some help. My current goal is to change the source of an iFrame to a specific link ...

What is the best way to gather Data URI content through dropzone.js?

I am currently utilizing Dropzone for its thumbnail generation feature and user interface. However, I am only interested in using the thumbnail generation ability and UI and would prefer to collect all the data URIs myself and send them to the server via a ...

Issue with forkJoin in the share component (and merging boolean variables) is not defined

I am facing an issue with my service where I need to share the result of a forkjoin, but the component is showing up as undefined Here is my service logic layer: @Injectable({ providedIn: 'root' }) ...

What is the best way to show a pop-up modal in Vue.js?

Having some trouble getting the Vue Modal to work in my Vue-cli setup for reasons unknown. Attempting to implement the modal example from: https://v2.vuejs.org/v2/examples/modal.html I'm still fairly new to Vue, so bear with me and my basic question. ...

Transfer the contents of a field in an Object Array to a new simple Array using PHP

My PHP Object Array has multiple fields that need to be extracted and stored in separate arrays in order to pass them to a bash script. Since bash is not object oriented, having individual arrays is preferred. This is what I am attempting to achieve: < ...

"Angular encountering an error with converting a string to a date due to

I have a date stored as a string in the format '2022-07-15T09:29:24.958922Z[GMT]'. When I try to convert it to a date object, I am getting an error saying it is an invalid date. Can anyone help me with this issue? const myDate = response; / ...

AngularJS: Dealing with scope loss in a directive following a promise

I am currently facing a major issue within my Angular application. There is a Factory in my code that makes an HTTP request to retrieve spoolers and returns a promise. Spooler.prototype.load = function () { var self = this; var deferred = $q.defe ...

Guide on how to restrict specific days and dates in MUI React datepicker using a JSON array

I am working on a Laravel application that generates a JSON response containing dates and days of the week that need to be disabled in the datepicker. For instance, here is an example of my datesOff constant when I log it: ['2022-05-08', '2 ...

Class name that changes dynamically with a specific prefix

I am attempting to dynamically assign ng-model names so that they can be accessed in the controller using '$scope.numbers.no1', '$scope.numbers.no2', and so on. However, my current code is not producing any results: <div ng-repeat=" ...

Unselecting an "all selected" checkbox

I need help with my checkbox functionality. Currently, I have a checkbox that selects all options when clicked, but if one option is deselected, the "Select All" option remains checked. Any guidance on how to address this issue would be greatly appreciated ...

What is the most efficient method for choosing a class with jQuery?

I'm dealing with a Bootstrap button: customtags/q_extras.py @register.filter(name='topic_check') def is_topic_followed(value, arg): try: topic = Topic.objects.get(id=int(value)) user = User.objects.get(id=int(arg)) ...

Conclude the execution of promises after a for loop

I'm looking to enhance my code by ensuring that it waits for the asynchronous query called prom to finish before resetting the array and restarting the first for loop. This way, the array will be cleared before the loop begins again. items = []; var ...

How does Code Sandbox, an online in-browser code editor, manage file storage within the browser?

What are the ways in which Code Sandbox and StackBlitz, as online in-browser code editors, store files within the browser? ...

Adding a new field to an embedded document in MongoDB (without using an array)

My task involves updating a json document in mongodb by single field. Despite the simplicity if my data was in an object array, it's more complex due to objects within objects caused by early design choices and reasons. This is the structure of the s ...

Creating a smooth fading effect for an element within a react component

I am currently working on implementing a fade out warning/error message (styled with Bootstrap) in a React component, however, I am encountering some challenges with the timing of the fade-out effect. Up to this point, the fade out effect is functioning c ...

ASP.NET MVC with AngularJS issue: post request does not trigger redirection

Why is the RedirectToAction not working and the URL does not change to /Home/Second when I make a post request to the Login? Using AngularJS: $scope.answer = function(answer) { $mdDialog.hide(answer); $http({ method: 'POST', url ...

Utilizing Matrix Distance Genetic Algorithm for Mobile Applications

I am working on an Android routing application that allows users to input travel time in hours, and my app generates possible routes for them. To determine the routes, I am using a genetic algorithm (GA) implemented in PHP. However, I face a challenge reg ...

What is the best way to extract data from my json file stored in the assets folder using Kotlin

Is there a way to effectively parse a JSON file using Kotlin? While there are several solutions available online, they all seem to be the same and do not suit my specific needs. Sample of my JSON file: { "A": [ { "co ...