What is the best way to loop through this JSON object without using jQuery?

I have a json object that I obtained using

var jsonObj = json_encode( <?php echo $php_array ?>);
. It looks different from the typical format, such as what is shown on w3schools:

{
    "employees": [
        { "firstName":"John" , "lastName":"Doe" }, 
        { "firstName":"Anna" , "lastName":"Smith" }, 
        { "firstName":"Peter" , "lastName":"Jones" }
    ]
}

My json structure is completely different:

{"PINEFOREST JEWELRY":
    ["3034.25","2002-01-02"],
"AMBERS DESIGN":
    ["2034.75","2002-01-02"],
"ELEGANT JEWELERS":
    ["206","2002-01-02"],
"SALEM'S JEWELERS":
    ["406","2002-01-02"]}

Is it possible for me to iterate through this json object?

Answer №1

To access the object's immediate properties, a for loop can be utilized in the following manner:

let value;
for(let prop in object) {
    if(object.hasOwnProperty(prop)){
        value = object[prop];
        console.log(value);
    }
}

Answer №2

One way to iterate through nested data structures is by using a combination of for in and for loops.

for (var category in items) {
    for (var index = 0; index < items[category].length; index++) {
        console.log(items[category][index]);
    }
}

Answer №3

Absolutely! You can iterate through it since it is valid json data.

In order to begin, you must first convert the json into a format that JavaScript can iterate over using JSON.parse() (MDN). Assuming that the 'json' mentioned earlier is a string of 'json', the process would look like this:

var accessories = JSON.parse(myJson); // Replace myJson with your actual variable holding the json

Now, you have an object that you can iterate through. One simple way to achieve this is by utilizing Object.keys() (MDN) along with Array.forEach() (MDN) in this manner:

Object.keys(accessories).forEach(function (key) {
    console.log(key); // Will display 'PINEFOREST JEWELRY' on the first iteration
    accessories[key].forEach(function (price) {
        console.log(price); // Should show '3034.25' initially
    }
});

Give it a shot, or explore other solutions suggested by fellow contributors – both approaches are effective. However, this method aligns with my preference for handling such scenarios!

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

Creating a versatile Google line chart with multiple series that have varying datetime values

I am faced with the challenge of handling an unspecified number of data sets within a JSON feed. The uncertainty lies in not knowing how many datasets will return - it could be one, twelve, thirty, or any other number. Each dataset consists of a date and a ...

Why does starting up the Firebase emulators trigger the execution of one of my functions as well?

Upon running firebase emulators:start --only functions,firestore, the output I receive is as follows: $ firebase emulators:start --only functions,firestore i emulators: Starting emulators: functions, firestore ⚠ functions: The following emulators are ...

How can I ensure that the div remains fixed on scroll and appears directly below the navigation bar, rather than at the top of the page?

There is a div (#callback) that loads asynchronously via ajax upon submit, for updating or deleting an item. It appears as the green message box at the top of the page. Click here to see image and this is how it looks when "scrolling": Check out the scrol ...

Stopping CSS animations at a specific point along the path without using timing functions can be achieved by implementing a targeted

Is there a way to pause an animation at the 50% mark for 2 seconds and then resume? P.S. The setInterval method is not recommended! function pauseAnimation() { document.getElementById("0").style.animationPlayState = "paused"; }; var pauseInterval = set ...

Unable to load circles on page refresh with amCharts Maps

I am experiencing an issue with the functionality of my amCharts maps. Whenever I refresh the page, the circles that are supposed to be displayed disappear. However, when I zoom in, the circles reappear. This problem has me puzzled, and I'm not sure ...

Would appreciate guidance on incorporating breadcrumbs into the JSP code provided below. Thank you for your help!

I need assistance with implementing breadcrumbs in these hyperlinks to enable tracking. String cat_code= fetch.getCat_code(); %> <% if(P_list!=null && P_list.size()>0) { for(int i=0;i <P_list.size();i++) { b=( Bean)P_list.get(i); % ...

"After completing the task, the textview does not get updated in onpost

I am currently working on creating a movie catalogue app and facing an issue with the DetailActivity. The problem arises when I click on the first movie to view its details, then press the back button. Upon clicking on another movie, the app still displays ...

Is it possible to create a pitch shifter with the web-audio-api?

Creating a Pitch Shifter with Node.js Hello, I am new to web development! I am currently working on developing an online audio player that requires a pitch shifter. I have been attempting to grasp the concept of the web audio API, but find it challengin ...

Having trouble transferring form data from a React.js form to a Flask API, as it is not permitting submission to MongoDB

I am currently working on a project to create a user form using react.js, python (Flask), and mongodb. Unfortunately, I am facing an issue where none of the input data is being sent to the Flask backend. Does anyone know how I can troubleshoot this problem ...

Utilizing regular expressions on a URI parameter in JavaScript

I implemented an ajax function that retrieves three images (PORTRAIT, SQUARE, and LANDSCAPE) from a JSON response: $.ajax({ url: link, method: 'GET', headers: { "Authorization": authToken ...

I am encountering an issue with the appendChild() method when trying to create a new element using createElement("ul")

I am facing an issue with creating a UL and LI elements beneath the P tag. Would appreciate it if someone could review my code below. The javascript is showing the following error message: Uncaught TypeError: thisIsQuizContainer.appendChild is not a fu ...

I'm attempting to streamline my code...what is preventing me from achieving this?

As someone who is self-taught in the ways of coding, I'm looking to streamline my JavaScript code. I have two divs with classes a0 and a1, and I want to add a mouseenter event to each one (using the same event). You can check out my JSFiddle for a be ...

Integrate the dForm plugin with a convenient time picker widget

Currently, I am attempting to integrate a time picker widget into a jQuery plugin called dForm. The specific timepicker widget can be found at the following link: https://github.com/jonthornton/jquery-timepicker Despite reviewing the dForm documentation, ...

I encountered an issue while using the tab bar feature in Bootstrap where I wasn't able to navigate back to the first tab or any

My current project involves JavaScript, and I integrated a Bootstrap tab bar component. However, when I try to run the code in Google Chrome, I encounter an issue. The first time I select the first tab, the content displays correctly. But when I select the ...

Generating a Stream for FormData implementation

I am currently utilizing an API to import a CSV file. The CSV file is generated in memory from a String and then uploaded using the request module. However, I am encountering difficulties in creating a Readable Stream from the String. To resolve this issue ...

How can jsPDF be used with Angular2 in Typescript?

Recently, I developed an Angular2 application that is capable of generating JSON data. My main goal was to store this JSON output into a file, specifically a PDF file. This project was built using Typescript. To achieve the functionality of writing JSON d ...

Having trouble with custom popup message rendering but the button is unresponsive?

I am currently experiencing an issue with a custom popup that is supposed to display upon form submission. The popup shows up, but there seems to be a problem with the close button functionality. Even though you can click on the X button, it does not close ...

Exploring the capabilities of Set() and the for..in loop in JavaScript

function removeDuplicates(menuArray) { let flatmenus = menuArray.flat();//This method combines child and parent arrays into one unique array let combinedMenu = new Set();//Creates an object that removes duplicate elements flatmenus.forEach(dish => ...

Numerous features

My goal is to create a program with two functions - one for addition and one for multiplication. For example, if I input 5 and 6, the calculate button should output 11 and 30, respectively. Should I combine both functions into one or keep them separate? An ...

HTML code with embedded messages

I am interested in creating a straightforward message forum system. My goal is to organize messages in a nested structure (answering questions). For my website, I want it to be in Hebrew (dir="rtl"). I am considering generating <ol> elements dynam ...