Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return all the values of an array in json

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?

like image 305
Tiago Barreto Avatar asked Jan 19 '26 17:01

Tiago Barreto


2 Answers

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);
    
like image 59
Oriol Avatar answered Jan 22 '26 07:01

Oriol


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

like image 34
OzerGul Avatar answered Jan 22 '26 07:01

OzerGul