将json数据循环到for循环中 [英] Loop json data into for loop

查看:562
本文介绍了将json数据循环到for循环中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨Ppl,



我试图将Json ouptut循环到for循环并将它们存储到另一个数组中,因为我只需要来自Json的特定值... 。



这里是代码...我无法获取DTSTART,DTEND字段..我猜它是因为命名..我无法改变param名字,因为我从输出中收到它。



任何想法如何获得这些id的值?谢谢



Hi Ppl,

I am trying to loop the Json ouptut into for loop and store them into another array as i need only specific values from Json....

here is below code... i am unable to fetch DTSTART,DTEND fields.. i guess its because of naming.. i wont be able to change the param names as i receive it from output.

Any idea how to get the value of those ids also? Thanks

<!DOCTYPE html>
<html>
<body>

<p>Looping through arrays inside arrays.</p>

<p id="demo"></p>

<script>

var myObj, i, j, x = "";
myObj = {
      "cars": [
        {
		"DTSTART;TZID=America/New_York": "20170211T123000",
		"DTEND;TZID=America/New_York": "20170211T133000",
		"RRULE": "FREQ=WEEKLY;BYDAY=SA",
		"DTSTAMP": "20170213T195454Z",
		"UID": "ks0lgptphtr46rdt4a6p94l2f8@google.com",
		"CREATED": "20170211T152911Z",
		"DESCRIPTION": "",
		"LASTMODIFIED": "20170211T152911Z",
		"LOCATION": "",
		"SEQUENCE": "0",
		"STATUS": "CONFIRMED",
		"SUMMARY": "monday meeting",
		"TRANSP": "OPAQUE"
	}
    ]
}

for (i in myObj.cars) {
    x += "<h1>" + myObj.cars[i].SUMMARY + "</h1>";
     x += "<h1>" + myObj.cars[i].DTSTART + "</h1>";
   
}

document.getElementById("demo").innerHTML = x;

</script>

</body>
</html>





我尝试过:



以下是执行代码



Tryit Editor v3.3 [ ^ ]

推荐答案

好的,由于键命名的未定义错误,键名为DTSTART; TZID = America / New_York 而不是DTSTART。根据您描述的情况,这里有一个使用/ startsWith等键访问数组值的替代方法。现在,您的下一个任务是弄清楚如何以您喜欢的顺序显示结果,因为循环从上到下开始。



Ok, the undefined error because of the key naming, the key name is "DTSTART;TZID=America/New_York" and not "DTSTART". Based on the circumstances you describe, here is an alternative to access the array value using key like/startsWith. Now, your next assignment is to figure out how to display the result in the order that you prefer because the loop start from top to bottom.

for (var i = 0; i < myObj.cars.length; i++){
    var obj = myObj.cars[i];
    for (var key in obj){
    
    	if (key == "SUMMARY") {
         	x += "<h1>" + obj[key] + "</h1>";
        }
        
        if (key.startsWith("DTSTART")) {
         	x += "<h2>" + obj[key] + "</h2>";
        }
    }
}





输出

20170211T123000

星期一会议



Output:
20170211T123000
monday meeting


就像添加square []一样简单,即
It is as simple as adding a square [], i.e.
myObj.cars[i]["DTEND;TZID=America/New_York"]

尽管如此,尽量避免像这样的异常密钥,因为它会打破那些通常的JSON处理代码。

Nevertheless, try to avoid unusual keys like this as it is going to break those usual JSON handling code.


这篇关于将json数据循环到for循环中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆