Exploring object properties to access JSON arrays

Consider this scenario with a JSON file:

{
  "shows": [
             {
               "name": "House of cards",
               "rating": 8
             },
             {
               "name": "Breaking bad",
               "rating": 10
             }
  ]
}

I am interested in retrieving the rating of a show based on its name. Here's an example code snippet:

var rating = data.shows["House of cards"].rating;

Is there a way to achieve this or something similar? Thank you very much!

Answer №1

If you're trying to access data from a JSON sample, simply deserializing it won't give you hash-style access.

One approach could be re-structuring the JSON and using object literals for your shows:

{
    "shows": {
         "House of cards": {
             "rating": 8
         }
     }
}

Afterwards, you can get an array of show keys by using Object.keys(...):

Object.keys(x.shows);

You also have the option to modify the structure post deserialization:

var x = { shows: {} };

for(var index in some.shows) {
   x.shows[some.shows[index].name] = { rating: some.shows[index].rating };
}

// Accessing a show
var rating = x.shows["House of cards"].rating;

I recommend converting the data in this way to enable easy plain JavaScript access to your shows, without requiring full iteration through the show array.

By utilizing object literals, accessing properties becomes similar to a dictionary or hash table method, eliminating any need for a search function in the background.

Update

If you are wondering how to iterate through shows once they are in an associative array/object format instead of a regular array:

Object.keys(shows).forEach(function(showTitle) {
    // Perform actions for each iteration here
});

Alternatively...

for(var showTitle in shows) {
    // Perform actions for each iteration here
}

Update 2

For a functional example, check out this jsFiddle demo: http://jsfiddle.net/dst4U/

Answer №2

Give this code a shot:

let tvShows = {
  "series": [
             {
               "name": "Stranger Things",
               "rating": 9
             },
             {
               "name": "The Crown",
               "rating": 7
             }
  ]
};
tvShows.series.forEach(findRating);

function findRating(show, index, showsArray) {
  if( show.name == 'Stranger Things' ) {
    console.log( showsArray[index].rating );
  }
}

Answer №3

Check out this Fiddle example

var data = {"shows": [{"name": "Stranger Things","rating": 9},{"name": "The Crown","rating": 8}]};
var shows = data.shows;
var showToFindRating = "Stranger Things";
for(var a in shows){
    if(shows[a].name == showToFindRating){
       alert("The rating for "+ showToFindRating+ " is " +shows[a].rating);
    }
}

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

After successfully authenticating, you may introduce a new React component

Currently, I am working on a page that will only display information once a user has logged into their account. I have successfully implemented an authentication system using NodeJS, and now my goal is to restrict access to specific components or pages bas ...

Discovering whether an ID exists within a variable containing HTML code

I am currently attempting to determine if the ID is included in a variable containing HTML content. The ID name is being added to a DIV element through dynamic variables. strHTML = "<div id='"+var1+var2+"'>" Now, I want to verify if a sp ...

Fetching data from API with React Router

Recently, I started learning React and am currently working on an application that needs to retrieve data from an API. I have created a component that is responsible for fetching the data, receiving a JSON object in return, and populating a table with it. ...

In JavaScript, how does the usage of parentheses change the functionality of a function?

function find() { console.log("Request handler 'find' was called."); } function display() { console.log("Request handler 'display' was called."); } exports.find = find; exports.display = display; There ...

Your request was denied by the Google Maps API server due to an invalid request. Please include the 'size' parameter in your request

I need to incorporate a static Google Map into my application built on node.js. Here is the code snippet: .panel.panel-primary .panel-heading h2.panel-title On the map .panel-body img.img-responsive.img-rounded(src="http://maps.googl ...

Assigning identifiers to phrases located in separate hierarchical dictionaries

I have developed a method for extracting sentences from a specific key within a nested file. I am now aiming to enhance this method by adding a label every time it encounters a new dictionary. Whenever the value HEADER appears, it signifies the beginning ...

Disabling the "Master Detail" feature in MUI

Exploring the functionality of MUI's Master Detail feature raised a question about CSV exporting from a Data Grid. When trying to export to CSV with the Master Detail implementation, the export functionality seemed to break (as expected). It technical ...

Prevent certain images from loading by blocking them

I am trying to create an extension that blocks two specific images from loading. Initially, I attempted to achieve this by using the following code in the content.js file: $("#rated-image").remove(); //id of one image $(".blur-mask").remove(); //class of ...

Unraveling the Mystery of React Event Bubbling: Locating the Desired

I am working with a <ul> Component that wraps several <li> Components. To streamline my code, I would like to avoid adding an individual onClick handler to each li and instead utilize a single handler on the parent ul element to capture the bub ...

Design the parent element according to the child elements

I'm currently working on a timeline project and I am facing an issue with combining different border styles for specific event times. The main challenge is to have a solid border for most of the timeline events, except for a few instances that share a ...

Typescript - Promise resolves prematurely

I have been given a code with three essential parts that cannot be altered: 1. First, there is a call to the getData function, followed by printing the output. getData().then(console.log); 2. The function signature is as follows: async getData(): Promise ...

What is the functionality of the remote data source in Jquery Mobile autocomplete feature?

Currently, I am browsing through this page and it appears that there is no clear documentation provided on the expected format or functionality of the remote data source. The example JavaScript code on the website references a remote data source at http:/ ...

Difficulty understanding how to deserialize a JSON object in a class

After using json2csharp.com to generate class for deserializing my Json raw data, I ended up with multiple classes like "__invalid_type__" and "RootObject", which has left me feeling confused. My current dilemma is whether I should incorporate the __inval ...

What does the client perceive or not perceive? Node.js, JavaScript, MySQL

For a university project, I am tasked with creating a web application that is compatible with both desktop browsers and mobile devices. The technologies I will be using include HTML, CSS, JavaScript, Node.js, and MySQL. I have recently familiarized myself ...

CSS responsive grid - adding a horizontal separator between rows

I currently have a responsive layout featuring a grid of content blocks. For desktop view, each row consists of 4 blocks. When viewed on a tablet, each row displays 3 blocks. On mobile devices, each row showcases 2 blocks only. I am looking to add a ho ...

How can one access the owner function from a different function?

Check out the example on jsfiddle: https://jsfiddle.net/cg33ov4g/3/ (function($){ var foo='foo_value'; var bar='bar_value'; function getVar(theVar){ console.log(this[foo]); console.log(this[bar]); //the c ...

"The Vue component's data is successfully updating within a method using setInterval(), however, the changes are not reflected in the DOM

I have a function in my methods that gets triggered with a @click in the view. The function starts a timer, and although it seems to work fine in the DevTools, the timer only updates in the DevTools when I refresh the page. Moreover, in the view, the time ...

Utilizing Material UI Pickers and Formik to efficiently handle Date, Time, and Second components

Currently, I am developing a React application with Formik that requires the utilization of date and time pickers. The app is being constructed using Material-UI and I have been exploring the possibilities provided by Material-UI Pickers at Given my relat ...

Guide to dynamically add tr element using CSS to a table

While using the $.each function in jQuery, I am retrieving data and adding it to a table in the following manner: $.each(segment, function (index, innerSegment) { var tr; tr = $('<tr/>'); tr.append("<td>" + segment[i].Airline.Air ...

NodeJS - Promise resolution results in an empty object being returned

Lately, I have been revamping my simple server and attempting to incorporate promises. However, despite having data in my mongoDB database (specifically a list of categories), when I invoke the method below, it returns an empty JSON object {}. I've ex ...