I need a little help with a loop in JavaScript. Please see the JSON data below
{
"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
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?
CodePudding user response:
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.
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)
}
}