In my JavaScript code, I am parsing a JSON file and attempting to extract the data associated with a specific key

Here's the javascript code I'm working on. I am looping through a JSON file and trying to access the 'bought_together' values nested under 'related', but my current code doesn't seem to be doing what I want it to do. To debug, I'm using `document.body.innerHTML = 'hello';` to check if my if statement is functioning correctly. If this explanation is unclear, please let me know.

$(function() {
  $.getJSON('test.json', function(data) {
    $.each(data.products, function(key, val) {
      for (var i = 0; i < data.products.length; i++) {
        var obj = data.products[i];
        if (obj.related == 'bought_together') {
          document.body.innerHTML = 'hello';
        }
      }

    });
  })
})

Below is a snippet of the JSON file I'm referencing.

{
  "products": [{
    "asin": "B0001MQ60A",
    "title": "KEEN Men's Newport H2 Sandal",
    "imUrl": "http://ecx.images- 
    amazon.com / images / I / 41 pRaO7fFSL._SX395_.jpg ",
    "related": {
      "also_bought": ["B000MN8OR6"],
      "also_viewed": ["B0000DYKET", "B0035FE60M", "B008KI85R4", "B000MQWVA4",
        "B003Z4KHXS", "B00GUBOCGQ",
        "B003O2SLXY", "B0017KSRMA", "B003O2SBKM", "B00DSN637U", "B000HDJ8IK", "B00E0J3HVG", "B003Z4KGZW",
        "B005HO2CYG", "B003H4QFVY", "B0017LB2VC", "B002R8JPTK", "B008KI84SE", "B005DJDL9A", "B003TU14OE",
        "B00E0J3HTI", "B000EDTVYY", "B003Z4JOJG", "B00DSN638E", "B00E0J3HVQ", "B008KI88JY", "B00EZIRE20",
        "B0095RGEH2", "B00CEX6MSU", "B000B84URK", "B003O2SPMG", "B002KKCWP4", "B003O2SLXE", "B00JQHFV0M",
        "B008JE8V14", "B0055ATVDW", "B003Z4KLMA", "B008ZAY40Y", "B003H4QFV4", "B00DSN64BU", "B002KKCZLA",
        "B0055ATVV4", "B00HFY47JY", "B00DPHJUTW", "B008FWRJ6I", "B003Z4JUFO", "B00JFB4RL8", "B00HR1LTNM",
        "B005HMTPBG", "B00KCT84I4", "B00HXDITEG"
      ],
      "bought_together": ["B003O2SLXY", "B003H4QFVY", "B002R8JPTK", "B000EDTVYY"]
    },
    "salesRank": {
      "Shoes": 18
    },
    "categories": [
      ["Clothing, Shoes & Jewelry", "Shoes & Accessories: International Shipping Available"],
      ["Clothing, Shoes & Jewelry", "K", "Keen"],
      ["Clothing, Shoes & Jewelry", "Comfort Shoes"],
      ["Clothing, Shoes & Jewelry", "Men", "Shoes", "Sandals"],
      ["Clothing, Shoes & Jewelry", "Men", "Shoes", "Athletic", "Sport Sandals"]
    ]
  }]
}

Answer №1

obj.related does not store a string, but rather an object -- therefore, the check should be for the existence of a key with the name "bought_together", not for the string itself:

// Data is shown in a variable for demonstration purposes instead of making an ajax call:
var data = {
  "products": [{
    "asin": "B0001MQ60A",
    "title": "KEEN Men's Newport H2 Sandal",
    "imUrl": "http://ecx.images-amazon.com/images/I/41pRaO7fFSL._SX395_.jpg",
    "related": {
      "also_bought": ["B000MN8OR6"],
      "also_viewed": ["B0000DYKET", "B0035FE60M", "B008KI85R4", "B000MQWVA4",
        "B003Z4KHXS", "B00GUBOCGQ",
        "B003O2SLXY", "B0017KSRMA", "B003O2SBKM", "B00DSN637U", "B000HDJ8IK", "B00E0J3HVG", "B003Z4KGZW",
        "B005HO2CYG", "B003H4QFVY", "B0017LB2VC", "B002R8JPTK", "B008KI84SE", "B005DJDL9A", "B003TU14OE",
        "B00E0J3HTI", "B000EDTVYY", "B003Z4JOJG", "B00DSN638E", "B00E0J3HVQ", "B008KI88JY", "B00EZIRE20",
        "B0095RGEH2", "B00CEX6MSU", "B000B84URK", "B003O2SPMG", "B002KKCWP4", "B003O2SLXE", "B00JQHFV0M",
        "B008JE8V14", "B0055ATVDW", "B003Z4KLMA", "B008ZAY40Y", "B003H4QFV4", "B00DSN64BU", "B002KKCZLA",
        "B0055ATVV4", "B00HFY47JY", "B00DPHJUTW", "B008FWRJ6I", "B003Z4JUFO", "B00JFB4RL8", "B00HR1LTNM",
        "B005HMTPBG", "B00KCT84I4", ...
      ],
      "bought_together": ["B003O2SLXY", "B003H4QFVY", "B002R8JPTK", "B000EDTVYY"]
    },
    "salesRank": {
      "Shoes": 18
    },
    "categories": [
      ["Clothing, Shoes & Jewelry", "Shoes & Accessories: International Shipping Available"],
      ["Clothing, Shoes & Jewelry", "K", "Keen"],
      ["Clothing, Shoes & Jewelry", "Comfort Shoes"],
      ["Clothing, Shoes & Jewelry", "Men", "Shoes", "Sandals"],
      ["Clothing, Shoes & Jewelry", "Men", "Shoes", "Athletic", "Sport Sandals"]
    ]
  }]
}



// As suggested in another response, either $.each or a for loop can be used, there is no need for both.
for (var i = 0; i < data.products.length; i++) { 
  var obj = data.products[i];
  if (obj.related["bought_together"]) {
    console.log("found: ", obj.related["bought_together"]);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Answer №2

Instead of using a for loop, you can utilize the existing $.each loop to iterate through your data items.

$(function() {

    $.getJSON('test.json', function(data) {
      $.each( data.products, function( key, val ) {
        if (Object.key(data.products.related).length) { // ensure that the related key exists
            if (data.products.related['bought_together']) { 
               document.body.innerHTML = 'hello';
            }
        }
    });
    })})

If you still prefer to use a for loop, make sure not to nest it inside the $.each loop.

...

    for (var i = 0; i < data.products.length; i++) {
        var obj = data.products[i];

        if (obj.related['bought_together']) { // return undefined if does not exist
             document.body.innerHTML = 'hello';
        }

    }

Answer №3

In the realm of programming, data.products[i].related is not a mere string but an array. So, in order to determine its existence, you could employ

typeof data.products[i].related !== "undefined"

Alternatively, if it consistently exists and you wish to ascertain whether it has any elements:

data.products[i].related.length>0

Answer №4

If you're looking to verify the existence of the "bought_together" property and, if true, display "hello" in your document.

You can achieve this more efficiently with the following approach:

var jsonText = '{ "products": ['+
'{'+
'"asin": "B0001MQ60A",'+
'"title": "KEEN Men\'s Newport H2 Sandal",'+
'"imUrl": "http://ecx.images- amazon.com/images/I/41pRaO7fFSL._SX395_.jpg",'+
'"related": {'+
'  "also_bought": ["B000MN8OR6"],'+
'  "also_viewed": ["B0000DYKET", "B0035FE60M", "B008KI85R4", "B000MQWVA4"],'+
'  "bought_together": ["B003O2SLXY", "B003H4QFVY", "B002R8JPTK", "B000EDTVYY"]'+
'},'+
'"salesRank": {"Shoes": 18},'+
'"categories": ['+
' ["Clothing, Shoes & Jewelry", "Shoes & Accessories: International Shipping Available"],'+
' ["Clothing, Shoes & Jewelry", "K", "Keen"], ["Clothing, Shoes & Jewelry", "Comfort Shoes"],'+
' ["Clothing, Shoes & Jewelry", "Men", "Shoes", "Sandals"],'+
' ["Clothing, Shoes & Jewelry", "Men", "Shoes", "Athletic", "Sport Sandals"]'+
']}'+
']}';

jsonObj = JSON.parse(jsonText);

var found = jsonObj.products.find(product => product.related && !!product.related["bought_together"]);

if (found) {
document.body.innerHTML = 'hello';
}

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

Using vuex-class to interact with Vuex in non-Vue components

Is it possible to access Vuex outside of a Vue component using vuex-class? In a typical scenario, the process is quite straightforward: // some JS file import store from './../store'; // path to Vuex store store.commit('ux/mutationName&ap ...

Prevent a sliding panel from responding if there is no input text by incorporating jQuery

I have a straightforward example of user input and a button that reveals "Hello World" when clicked: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1 ...

Having trouble establishing a connection with both MySQL and MongoDB in NestJS with TypeORM

Recently, I ventured into learning about NestJS and attempted to create an application that connects to both mysql and mongodb databases. However, after several unsuccessful attempts, I encountered the following error: Nest can't resolve depende ...

Stopping setinterval on click can be achieved by using the clearInterval function in

I've encountered an issue while using a slideshow on my website. The plugin I'm using does not have an autoplay feature, so I had to implement it using setinterval in my code. Below is the code I used: var myInterval, startInt = function(){ ...

Tips for safeguarding your passwords across diverse authentication methods

Exploring a new project idea, I am interested in supporting the SASL Mechanisms for authentication, particularly PLAIN and DIGEST-MD5. I am curious about how to securely store users' passwords when implementing these two authentication methods. When ...

Disregard the Json information if the property is not present

I attempted to retrieve the id Field dynamic post = fb.Get("/" + radListControl2.SelectedItem + "/feed?fields=message"); int count = (int)post.data.Count; for (int i = 0; i < count; i++) { radListControl1.Items.Add(Convert.ToString(post.data[i].i ...

Show items in the sequence of clicking

Is there a way to display elements in the order they're clicked, rather than their order in the HTML using jQuery? For example: CSS code: .sq{ display:none; } HTML Code: <a href="#" id="1">A</a> <a href="#" id="2">B</a> ...

Lack of Typescript 2.1 and Angular 2 type definitions with browserify

` vscode 1.7 Typescript 2.1.1 Angular 2 latest package.json "dependencies": { "@angular/common": "^2.2.4", "@angular/compiler": "^2.2.4", "@angular/core": "^2.2.4", "@angular/platform-browser": "^2.2.4", "@angular/platform-browser-dyna ...

Analyzing information with PHP, JSON, and SQL

I have encountered a few issues with the code I have been working on, but I was able to fix most of them. Currently, I am left with two notices and two warnings. However, these notices and warnings are essentially duplicates of the same problem, so I only ...

Trouble receiving Ajax response

Below is the code snippet I am working on: function f(){ var value = ""; var request1 = $.ajax({ url : '/a', type: "GET" }); var request2 = $.ajax({ url: '/b', type: ...

Show data from the road when hovering over gmaps.js

When a user hovers over a road, I want to display information similar to an infoWindow for a Marker. This is my code for drawing roads using gmaps.js: <script type="text/javascript"> var map; $(document).ready(function () { var map = new GM ...

Function used to update database through AJAX technology

I have implemented a PHP script to update my database using AJAX, and it is working correctly after being tested. To pass the required two variables to the PHP script for updating the database, I created a JavaScript function that utilizes AJAX to call the ...

Arranging an array of numeric values without utilizing the sort() function

Currently learning Javascript and I'm facing a challenge in an exercise from a tutorial, think it was learn street.com... The task is to sort an array of numbers without using the sort() method. Array looks like this: numbers =[12,10,15,11,14,13,16]; ...

Tips on how to retrieve the tooltip of an image that is only displayed when hovering over it using Selenium

Currently, I am in the process of learning Selenium and aiming to retrieve the tooltip displayed on an image in the Selenium console. The tooltip is set to only appear when hovering over the image. Despite my attempts to obtain the xpath and use actions, I ...

Encountered an error: Unexpected symbol < at the beginning of JSON data (JavaScript and PHP)

I've been struggling with this challenge for days and I hope someone can assist me with it. The issue revolves around passing data from JavaScript to PHP. My aim is to send the lostid from an HTML page to a JavaScript page, then have the JavaScript pa ...

Storing a portion of JSON data within a function called in the HTML document

I've been working with Angular and need to save a portion of JSON data in a variable within a function that is called in an HTML file: <select id="postazione" onchange="postazioneSelezionata()"> <option value="" selected disabled >Cho ...

The error encountered in the Node crud app states that the function console.log is not recognized as a

I am attempting to develop a CRUD application, however, I keep encountering an error message that states "TypeError: console.log is not a function" at Query. (C:\Users\Luis Hernandez\Desktop\gaming-crud\server\app.js:30:25) h ...

Convert JSON objects within an array into HTML format

Is there a way to reformat an array of JSON objects that has the following structure? [{"amount":3,"name":"Coca-Cola"},{"amount":3,"name":"Rib Eye"}] The desired output in plain HTML text would be: 3 - Coca-Cola 3 - Rib Eye What is the best approach to ...

Transmitting information through socket.emit from the client to the server

I'm facing an issue while trying to send numeric data from the client to the server using socket.emit. The problem is that the server doesn't seem to be receiving any data, as only `null` gets logged or I might be doing something wrong in my appr ...

Continuously encountering the error message "Controller does not have a default constructor"

Utilizing Spring MVC alongside the Jackson library for JSON (planning to integrate AngularJS later on). The issue arises when I start Tomcat, as the "No default constructor found" error is displayed. Below is the error log: SEVERE: StandardWrapper.Throwab ...