gpt4 book ai didi

javascript - 迭代 json 对象

转载 作者:搜寻专家 更新时间:2023-11-01 05:30:22 25 4
gpt4 key购买 nike

我在用纯 JavaScript 代码迭代 json 对象时遇到问题。 for 循环或 for each 循环会很棒,但我无法循环它。

//I want output in format like 
{
applicationGroupId:
[
treatmentIds
]
}

喜欢;

{
"879545457291368": [
879545457291370
],
"879545447124032": [
879545447124036,
879545447124034
]
}


<script>

var text = '{"treatmentApplicationGroupDataList": [{"applicationGroupId": 879545457291368,"treatments":[{"treatmentId": 879545457291370}]},{"applicationGroupId": 879545447124032,'+
'"treatments": [{"treatmentId": 879545447124036 },{"treatmentId": 879545447124034}]}]}';

var myObject = JSON.parse(text);

for(var i in myObject){

document.write(myObject.treatmentApplicationGroupDataList[0].applicationGroupId);
document.write(myObject.treatmentApplicationGroupDataList[0].treatments[0].treatmentId);

document.write(myObject.treatmentApplicationGroupDataList[1].applicationGroupId);
document.write(myObject.treatmentApplicationGroupDataList[1].treatments[0].treatmentId);
ocument.write(myObject.treatmentApplicationGroupDataList[1].treatments[1].treatmentId);

}

</script>

如您所见,我正在手动打印结果,但不是在 for 循环中。

最佳答案

正如您在示例中尝试做的那样,您可以使用 for-in 方法:

var text = '{"treatmentApplicationGroupDataList": [{"applicationGroupId": 879545457291368,"treatments":[{"treatmentId": 879545457291370}]},{"applicationGroupId": 879545447124032,"treatments": [{"treatmentId": 879545447124036 },{"treatmentId": 879545447124034}]}]}';

var myObject = JSON.parse(text);

// Using the for-in method
for (treatmentListId in myObject.treatmentApplicationGroupDataList) {
var curTreatmentList = myObject.treatmentApplicationGroupDataList[treatmentListId];

console.log(curTreatmentList.applicationGroupId+": ");

for (treatmentId in curTreatmentList.treatments) {
console.log("=>"+curTreatmentList.treatments[treatmentId].treatmentId);
}
}

或者您可以使用 .forEach method :

myObject.treatmentApplicationGroupDataList.forEach(function(treatmentList){
console.log(treatmentList.applicationGroupId+": ");
treatmentList.treatments.forEach(function(treatment){
console.log("=> "+treatment.treatmentId);
});
});

此处提供更多信息:For-each over an array in JavaScript?

关于javascript - 迭代 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31510222/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com