[英]Javascript loop through JSON with array
I need a little help with a loop in JavaScript. Please see the JSON data below我需要一些关于 JavaScript 循环的帮助。请参阅下面的 JSON 数据
{
"blogs":{
"id1":{
"title":"Title 1",
"date":"test_date",
"datestamp":"test_datestamp 1",
"content":"The content",
"url":"https:\/\/www.testlink1.com",
"tags":["move","New"]
},
"id2":{
"title":"Title 2",
"date":"test_date",
"datestamp":"test_datestamp 2",
"content":"The content 2",
"url":"https:\/\/www.testlink2.com",
"tags":["Netherlands","Yellow"]
}
}
}
Next I parse the JSON like below接下来我像下面这样解析 JSON
data = JSON.parse(this.response); //This JSON is the result from an AJAX call to a PHP file
For using the data I do this为了使用数据,我这样做
for(let id in data.blogs){
console.log(data.posts[id].date);
console.log(data.posts[id].title);
//etc.
}
But how can I loop the tags array inside this loop?但是我怎样才能在这个循环中循环标签数组呢?
I tried this but with no result我试过了但没有结果
for(let id in data.blogs){
for(let tag in data.blogs.tags){
alert(data.blogs[id].tags[tag]);
}
}
Who can help me with this?谁能帮我解决这个问题?
But how can I loop the tags array inside this loop?但是我怎样才能在这个循环中循环标签数组呢?
You need to identify the blog item currently in the process loop.您需要确定当前在流程循环中的博客项目。
Here due example, note the for-in
as you wrote or the for-of
loop to cycle the items.这里是适当的例子,请注意您编写的for-in
或用于循环项目的for-of
循环。
const data = { blogs: { id1: { title: 'Title 1', date: 'test_date', datestamp: 'test_datestamp 1', content: 'The content', url: 'https://www.testlink1.com', tags: ['move', 'New'] }, id2: { title: 'Title 2', date: 'test_date', datestamp: 'test_datestamp 2', content: 'The content 2', url: 'https://www.testlink2.com', tags: ['Netherlands', 'Yellow'] } } } for (const blogId in data.blogs) { const blogItem = data.blogs[blogId] console.log(`looping ${blogItem.title}`) for (const tag of blogItem.tags) { console.log(tag) } } for (const blogItem of Object.values(data.blogs)) { console.log(`looping ${blogItem.title}`) for (const tag of blogItem.tags) { console.log(tag) } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.