I have a json with all posts my blog and I wanna to return all the values of "tags" array. So, see the json example below:
"posts":[
{
"id":"89319077059",
"title":"Post Title 01",
"tags":[
"Politcs",
"Science",
]
},
{
"id":"89318918989",
"title":"Post Title 02",
"tags":[
"Football",
"Soccer",
]
},
]
So, I need to get the only tags values in loop, for example:
for (var i = 0; i < posts.length; i++) {
console.info("Here [i = 0] should be show the Politcs and Science and after [i = 1] show Football and Soccer");
}
I tried to create a other loop to search tags and using tags[1], tags[2], etc but don't works.
var tags = [];
for (var tag in posts[i].tags) {
tags.push(tag);
}
Any idea?
If I understand it well, you can use
Loop:
var tags = [];
for (var i = 0; i < posts.length; ++i) {
tags.push(posts[i].tags);
}
ES5 map:
var tags = posts.map(function(post){
return post.tags;
});
ES5 map + ES6 arrow functions:
var tags = posts.map(post => post.tag);
Here is code :
var posts = [
{
"id":"89319077059",
"title":"Post Title 01",
"tags":[
"Politcs",
"Science",
]
},
{
"id":"89318918989",
"title":"Post Title 02",
"tags":[
"Football",
"Soccer",
]
}
];
var tags = [];
for (var index in posts) {
var tagsArray = posts[index].tags;
tags.push(tagsArray);
}
console.log(tags);
Jsbin
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With