3

我有一个包含所有帖子的 json 我的博客,我想返回“标签”数组的所有值。因此,请参阅下面的 json 示例:

"posts":[
  {
     "id":"89319077059",
     "title":"Post Title 01",
     "tags":[
        "Politcs",
        "Science",
     ]
  },
  {
     "id":"89318918989",
     "title":"Post Title 02",
     "tags":[
        "Football",
        "Soccer",
     ]
  },
]

所以,我需要在循环中获取唯一的标签值,例如:

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");
}

我尝试创建另一个循环来搜索标签并使用标签 [1]、标签 [2] 等,但不起作用。

var tags = [];

for (var tag in posts[i].tags) {
     tags.push(tag);
}

任何想法?

4

5 回答 5

4

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);
    
于 2014-06-21T18:56:31.657 回答
1

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

于 2014-06-21T18:59:35.483 回答
1

In your for (var tag in posts[i].tags) loop, tag contains the keys, not the values.

So a quick fix would be:

for (var tag in posts[i].tags) {
    tags.push(posts[i].tags[tag]);
}

But as Oriol pointed out, for..in loops are meant to iterate through object properties, not arrays.

Just use a for loop like your first one.

于 2014-06-21T19:00:12.670 回答
1

尝试这个,

var posts = {"posts":[
  {
     "id":"89319077059",
     "title":"Post Title 01",
     "tags":[
        "Politcs",
        "Science",
     ]
  },
  {
     "id":"89318918989",
     "title":"Post Title 02",
     "tags":[
        "Football",
        "Soccer",
     ]
  },
]};


var tags = [];

for(var i=0;i<posts.posts.length;i++) {
    for(var j=0;j<posts.posts[i].tags.length;j++) {
        tags.push(posts.posts[i].tags[j]);
    }
}

console.log(tags);
于 2014-06-21T19:01:36.040 回答
1

您可以尝试使用 for 循环:

for (var i = 0; i < posts.length; i++) {
    for(var j = 0; j < posts[i].tags.length; j++) {
        console.log(posts[i].tags[j]);
    }
}

干杯。

于 2014-06-21T19:02:19.553 回答