简体   繁体   English

遍历嵌套的 JSON 并赋值给变量

[英]Traverse nested JSON and assign to variable

Related to my question from yesterday I have looked into JSON and decided to take it up.关于我昨天的问题,我调查了 JSON 并决定接受它。 The backend creates a json-response of following structure (from console log):后端创建以下结构的 json 响应(来自控制台日志):


{…}
​
    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.一个 header object (= Object 3 / 4 ) 显示它包含的每个 ZA8CFDE6331BD59EB2ACZ66F98。 Every data element will get a html wrapper with jquery.每个数据元素都将获得一个 html 包装器和 jquery。 So i need to know on which level the object is to set the appropriate wrapper.所以我需要知道 object 在哪个级别设置适当的包装器。 I've literally been driven insane during the last 3 hours.在过去的三个小时里,我真的被逼疯了。 So how can I traverse the JSON and every nested element?那么如何遍历 JSON 和每个嵌套元素呢?

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.我不确定您要实现什么,但您似乎想遍历 object 项目并相应地应用更改。 You can do this with recursion .你可以用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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