简体   繁体   中英

Traverse nested JSON and assign to variable

Related to my question from yesterday I have looked into JSON and decided to take it up. The backend creates a json-response of following structure (from console log):


{…}
​
    3: {…}
​​
        0: Object { probe_id: "4", date: "19.01.2021", start_time: "13:30", … }
​​
        1: Object { probe_id: "5", date: "20.01.2021", start_time: "13:30", … }
​​
        week_end: "24.01.2021"
​​
        week_start: "18.01."

    4: {…}
​​
        0: Object { probe_id: "6", date: "25.01.2021", start_time: "13:30", … }
​​
        week_end: "31.01.2021"
​​
        week_start: "25.01."

I basically need to display the data as in the response. One header object (= Object 3 / 4 ) that displays every object it contains. Every data element will get a html wrapper with jquery. So i need to know on which level the object is to set the appropriate wrapper. I've literally been driven insane during the last 3 hours. So how can I traverse the JSON and every nested element?

I'm not sure what are you trying to achieve, but it seems you want to traverse through the object items and apply changes accordingly. You can do this with recursion .

 var data = {0:{0:{ probe_id: "4", date: "19.01.2021", start_time: "13:30"},1:{ probe_id: "3", date: "19.01.2021", start_time: "13:30"}},1:{0:{ probe_id: "6", date: "25.01.2021", start_time: "13:30" }, week_end: "31.01.2021", week_start: "25.01." }}; traverse = (obj) => { for(const property in obj){ if(typeof obj[property] == 'object'){ traverse(obj[property]); } else { console.log(`Value is ${obj[property]}`); //perform some actions here accordingly } } } traverse(data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM