What might be causing the hasOwnProperty(key) method in JSON to return false?

I have successfully implemented a method to loop through the JSON data provided below:

{"dummmysetsJSONArr":[{"entryID":"1","distance":"100","calories":"50"},{"entryID":"2","distance":"200","calories":"100"},{"entryID":"3","distance":"300","calories":"150"},{"entryID":"4","distance":"400","calories":"200"},{"entryID":"5","distance":"500","calories":"250"},{"entryID":"6","distance":"600","calories":"300"}],"success":1}

This is how I am achieving this:

    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            myLogger(jsonarray[key].entryID + " - " + jsonarray[key].distance + " - " + jsonarray[key].calories);
        }
    }

However, my JSON data seems to be causing an issue with the if check in the for loop.

What might be going wrong with my JSON object?

My intention is to utilize the above for loop to populate data into google.visualization.DataTable() as shown below:

        data = new google.visualization.DataTable();
        data.addColumn('number', 'distance');
        data.addColumn('number', 'calories');

        for (var key in obj) {
            if (obj.hasOwnProperty(key)) {

                //data.addRow(jsonarray[key].distance);
                //data.addRow(jsonarray[key].calories);
            }
        }

Answer №1

If you are looking for a specific property in a collection, you can use the following code snippet (view example on jsbin):

var obj = {"dummmysetsJSONArr":[{"entryID":"1","distance":"100","calories":"50"},{"entryID":"2","distance":"200","calories":"100"},{"entryID":"3","distance":"300","calories":"150"},{"entryID":"4","distance":"400","calories":"200"},{"entryID":"5","distance":"500","calories":"250"},{"entryID":"6","distance":"600","calories":"300"}],"success":1};

for (var key in obj.dummmysetsJSONArr) {
    if (obj.dummmysetsJSONArr.hasOwnProperty(key)) {
        document.write(obj.dummmysetsJSONArr[key].distance + " " + obj.dummmysetsJSONArr[key].calories);              
        document.write("<br/>");
    }
}

Alternatively, you can search for objects that have specific properties like entryId, distance, and calories to account for any potential variability in your JSON structure.

Answer №2

It seems that you require several rounds of going through key/value pairs. During the initial iteration, you will retrieve the key 'dummmysetsJSONArr' along with an array as its value.

Subsequently, you will iterate through the array where each key represents the index and the value signifies the object.

Further traversal through the value will provide you with the attribute name of the object and its corresponding value.

Answer №3

To access the "dummmysetsJSONArr" property which is an array and not an object, you can use the following code:

var myObj = {"dummmysetsJSONArr":[{"entryID":"1","distance":"100","calories":"50"},{"entryID":"2","distance":"200","calories":"100"},{"entryID":"3","distance":"300","calories":"150"},{"entryID":"4","distance":"400","calories":"200"},{"entryID":"5","distance":"500","calories":"250"},{"entryID":"6","distance":"600","calories":"300"}],"success":1}
var obj = myObj.dummmysetsJSONArr; //this is an array not an object
var str = "";
for (var i=0;i< obj.length;i++) {     
    str += obj[i].entryID + " - " + obj[i].distance + " - " + obj[i].calories+"<br>";
}

Alternatively, as arrays in JavaScript are objects with numerical keys, you can also access it like this:

var obj = myObj.dummmysetsJSONArr; //this is an array not an object
var str = "";
 for (key in obj) {     
            str += obj[key].entryID + " - " + obj[key].distance + " - " + obj[key].calories+"<br>";
    }  

It is not necessary to check for hasOwnProperty since each property in your JSON object is its own property.

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

How can one safeguard their JavaScript code from potential threats and unauthorized access?

How can I ensure that a web app is not accessible or operated from the local file system? The app has a custom front-end workspace created with JS and various libraries, which should only be usable when the user is logged in to the domain with an active i ...

Update the text input field from a different webpage

I am working with two PHP pages, let's call them page1.php and page2.php. On page1.php, there is a textbox with a default value of 0, while on page2.php, there is a button. I have these two pages open in different tabs in a browser. My goal is to have ...

Conceal additional recipients in the "to" address field when sending emails with Node.js using Nodemailer

I am currently working on a project called EmailSender using node.js, and I have found that the nodemailer package is incredibly helpful. However, when sending emails to multiple contacts, all recipients are able to see each other's email addresses i ...

Showing data from the POST request in a dialog box

Greetings to all! I am in the process of building a webpage to test my API. The goal is to send a form to my nodejs backend and receive a JSON response back. So far, sending the request is functioning properly and I can track its progress on my VPS conso ...

Interchanging JSON and XML formats in C/C++ programming

I've been exploring various options but have yet to find a reliable set of routines for converting between JSON and XML in C or C++. While I've come across solutions in Javascript, Java, PHP, and Python, my json library is json-spirit. Currently ...

Issues with jQuery autocomplete functionality on certain elements are not uncommon

I've been experimenting with creating a user script for Opera using Greasemonkey to implement autocomplete functionality on input elements within web pages. However, I've encountered some issues with the script not working as expected. Initially ...

What are the steps to implement the "render" function from one class into another class within three.js?

As a newcomer to three.js, I have been working on creating a bowling game. However, I am encountering an issue where I need to access a function from my "Application" class within the physics class that I have created. Here is a snippet of the Application ...

Can a Spring MVC controller method return a JSONArray using @ResponseBody annotation?

I am facing an issue with AJAX while trying to load a URL that should return data from my controller in JSONArray format. However, when the call is made, I encounter a 406 not acceptable error. Is there any way to resolve this using @ResponseBody? Despite ...

Operating on a duplicate of the array is necessary for mapping an array of objects to function properly

I'm starting to uncover a mysterious aspect of Javascript that has eluded me thus far. Recently, I've been pulling an array of objects from a database using Sequelize. This array is quite intricate, with several associations included. Here' ...

Encountering an error while trying to add text: SyntaxError - Unexpected token 'for

I'm trying to print out the elements of an array using JavaScript. let listToArray = ["a","b","c"]; $(".tooltip").append(for(let i = 0; i < listToArray.length; i++) {listToArray[i]}); But I keep getting an error that says Uncaught SyntaxError: U ...

What are the steps for retrieving various JSON keys?

My task involves working with a JSON file in Python, where I need to access specific keys. The structure of my JSON file is as follows: { "spider":[ { "t":"Spider-Man: No Way Home (2021)", "u&q ...

Error: The hyperlink in the response from the Ajax request is not functioning as expected

I've exhausted all the suggestions for fixing this issue, but nothing has worked so far. Currently, my setup involves making an AJAX call to a PHP page called livesearch.php from the index page in order to retrieve live search results. <html> ...

Is Socket.io combined with Redis the best architecture for an interactive gaming experience?

My current setup involves a NodeJS scaling architecture with Redis, specifically designed for a real-time multiplayer game. However, I'm facing challenges in configuring separate lobbies for players, as the load balancer assigns users to different ser ...

Cypress: harnessing the power of regular expressions within jQuery selectors for the ":contains()" method

Trying to use Cypress along with a regular expression to target an element that includes specific text. The following get() function successfully works: cy.get('[data-cy=tile]').contains(new RegExp(myVar)) However, the following command does no ...

Utilizing Vue.js to track and navigate through browsing history using the browser's

I'm currently working on an application using Vue and Laravel. Instead of relying on vue-router, Laravel is managing my routes. Within my parent component, I am dynamically loading components based on the state of an object in the data. One of the m ...

Is it possible to manage the form submission in React after being redirected by the server, along with receiving data

After the React front-end submits a form with a POST request to the backend, the server responds with a JSON object that contains HTML instead of redirecting as expected. How can I properly redirect the user to the page received from the server? For inst ...

Looking for assistance in setting up an auto-suggest feature that displays retrieved or matched data from the database in a list format

I am currently facing an issue with the following problem: I have a form that includes a single search field with autosuggest functionality. I want to be able to type either a name or mobile number in this field. As I type, suggestions should appear base ...

Having trouble interacting with Bootstrap modal dialog when fullPage.js is active

Whenever I attempt to click on the button, a Bootstrap modal dialog box appears but remains unresponsive no matter what I try. My project utilizes both Bootstrap and fullPage.js http://codepen.io/anon/pen/obEOzO <body> <div id="fullpage"> &l ...

Having difficulty personalizing the email template on AWS SES

I am currently working on setting up a forgot password email system using AWS SES. Below is the template I have created: { "Template":{ "TemplateName": "forgotpasswrd", "SubjectPart": "Forgot ...

Are you ready to create a Modal Factory?

For a while now, I have been utilizing modals in various front-end frameworks to communicate with users in my applications. Typically, the process involves defining the modal's html and then rendering it through a click event. As my apps continue to ...