Extracting information from a JSON dataset

Struggling today to figure out how to loop through and print the name of each object.

Check out the JSON response below:

    {
        "placeListings": {
            "OBJ1": {
                "Active": true,
                "Name": "place 1"
            },
            "OBJ2": {
                "Active": true,
                "Name": "place 2"
            },
            "OBJ3": {
                "Active": true,
                "Name": "place 3"
            }
        }
    }

I want to extract the names using a for loop

 for (let i = 0; i < res.length; i++) {
                    console.log("NAME: " + res.placeListings.OBJ1.Name);
                }

However, I'm unsure how to go through OBJ1/OBJ2/OBJ3 etc...

If you have any guidance, please share!

Answer №1

The placeListings is actually an object, not an array. To access the keys of this object, you will need to utilize the Object.keys method.

const source = {
  placeListings: {
    OBJ1: {
      Active: true,
      Name: 'place 1'
    },
    OBJ2: {
      Active: true,
      Name: 'place 2'
    },
    OBJ3: {
      Active: true,
      Name: 'place 3'
    }
  }
}

const keys = Object.keys(source.placeListings)
console.log(keys)

for (let i = 0; i < keys.length; i++) {
  console.log(source.placeListings[keys[i]])
}

Answer №2

To simplify this task, you only need to write one line of code using the Object.keys() function combined with the Array.forEach() method.

Example :

const info = {
  "dataItems": {
    "ITEM1": {
      "Active": true,
      "Label": "Item A"
    },
    "ITEM2": {
      "Active": true,
      "Label": "Item B"
    },
    "ITEM3": {
      "Active": true,
      "Label": "Item C"
    }
  }
};

Object.keys(info.dataItems).forEach(item => console.log(info.dataItems[item].Label));

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

Having trouble getting any results from a JSON response using the jQuery Tokeninput plugin in PHP?

I am currently trying to implement the JQuery Tokeninput feature on my website. However, when I enter text into the search field, nothing appears and it just continues searching indefinitely... After reviewing the documentation, I noticed that the expecte ...

Upon sending an HTTP POST request from JavaScript to a Node server, the body was found to be

Trying to make an XMLHttpRequest from JavaScript to my node server. This is the request I am sending: var data = { "fname": "Fasal", "lname": "Rahman" }; var body = JSON.stringify(data); var xhttp = new XMLHttpRequest(); xhttp.open("POST", "/admin"); xhtt ...

Update the HTML weather icon with data from JSON

I have a collection of weather icons stored on my computer. How can I customize the default weather icons with my own set of icons? In the JSON file, there is a variable like this: "icon":"partlycloudy" <html> <head> <script src="http://c ...

Using JQuery to SlideUp with a Background Color Fading Behind an Image

I'm currently utilizing JQuery slideUp/slideDown functionality to create an overlay effect on an image. This overlay is initially hidden, only appearing when the mouse hovers over the image and sliding up from the bottom. The issue I'm facing is ...

JavaScript encountered an error stating that $ is undefined and has not been defined in the program

I am facing an issue while trying to submit a form in Django using AJAX. The error message displayed in the console is giving me a hard time in identifying the root cause. Despite trying several solutions, I have not been able to resolve this issue. Here i ...

Tips for integrating new channels and categories using a Discord bot

Hey there! I'm trying to add channels and categories, but I can't seem to get the function ".createChannel" working. The console keeps telling me that the function doesn't exist. I've been referencing the documentation at https://discor ...

What is the best method for storing API user authentication tokens in IBM cloud functions with Node.js?

I need to integrate my IBM cloud function with the Trello API, which requires user authentication. After redirecting them to the authentication page, a token is generated that I must save for future API calls. I heard that Node allows saving tokens to loc ...

Guide to eliminating hashtags from the URL within a Sencha web application

I'm currently developing a Sencha web application and I need to find a way to remove the "#" from the URL that appears after "index.html". Every time I navigate to a different screen, I notice that the URL looks like this: ...../index.html#Controller ...

Is there a way to store a JSON object retrieved from a promise object into a global variable?

var mongoose = require('mongoose'); var Schema = mongoose.Schema; const NewsAPI = require('newsapi'); const { response } = require('express'); const newsapi = new NewsAPI('87ca7d4d4f92458a8d8e1a5dcee3f590'); var cu ...

Using JSON Values in JavaScript

Below is a JSON result structured like this : [{"Januari":"0","Februari":"0","Maret":"0","April":"0","Mei":"7","Juni":"0","Juli":"0","Agustus":"0","September":"0","Oktober":"0","November":"0","Desember":"0"}] What is the best method to input these values ...

How to extract a value from a BehaviorSubject within an Angular 6 guard

I have chosen this approach because I have another guard responsible for validating the user based on a token that was previously stored. This is how it was handled in previous versions of rxjs, but now with the latest version you can no longer use map on ...

When loading a page in NodeJS and Express, there are no initial displays, but upon refreshing the page, all data is successfully retrieved

Struggling to solve this issue that has been lingering for a while. I'm currently working on a project where a remote JSON file is loaded into memory, parsed, and the results are displayed on the page (using pug). Everything seems to be working fine ...

ESLint flagging "Unexpected tab character" error with "tab" indentation rule enabled

Currently, my ESLint setup includes the Airbnb plugin (eslint-config-airbnb) along with the Babel parser. I recently decided to enforce the rule of using Tab characters for indentation instead of spaces. This is how my .eslintrc file looks like: { "p ...

Vue.js - Exploring methods to append an array to the existing data

I am looking to structure my data in the following way: Category 1 Company 1 Company 2 Company 3 Category 2 Company 1 Company 2 Company 3 Below is my code snippet: getlist() { var list = this.lists; var category this.$htt ...

What are the potential causes of receiving the error message "No Data Received ERR_EMPTY_RESPONSE"?

I often encounter this issue on my website, especially when I have a thread open. It seems to happen whenever I am actively checking for new posts and notifications via Ajax every 10 seconds or so. However, I'm not sure if this continuous reloading is ...

Creating Dynamic Types in TypeScript Based on React State

As part of my project, I am developing a versatile useFetch hook that will be responsible for handling data fetching operations. The hook should return an object with different properties based on whether the fetch operation was successful or encountered a ...

The syntax for specifying the post body content in frisby.js is important

My current setup involves smooth UI and server data exchange, but I am interested in exploring new development possibilities with Frisby.js. The UI utilizes a JavaScript form manager powered by jQuery. To send the request body, I first serialize a JavaScri ...

Assigning a dynamic name to an object in Typescript is a powerful feature

Is there a way to dynamically name my object? I want the "cid" value inside Obj1 to be updated whenever a new value is assigned. I defined it outside Obj1 and then called it inside, but when I hover over "var cid," it says it's declared but never used ...

Dynamically load scripts in angularJs

Having multiple libraries and dependencies in my angularjs application is posing a challenge as I want to load them all using just one script, given that three apps are utilizing these dependencies. Currently, I have this custom script: var initDependenci ...

What is the best way to pass my session token information between various JavaScript files on the server?

Here's the current status of my session tokens on the server: In my server.js file: app.use( session({ secret: "{ ...