问题描述:

I have an object with the following structure:

var PostsData = [

{

postId: 1,

postTitle: 'Cuba slam U.S. on human rights',

postExcerpt: 'Washington (CNN)U.S. and Cuban officials began a historic round of talks on Wednesday to bridge a 50-year rift in diplomatic relations, but just a day later, the Cuban delegation slammed the United States on its human rights track record.',

postTags: ['cuba', 'human rights', 'diplomatics', 'world']

},

{

postId: 2,

postTitle: 'YouTube stars interview Obama',

postExcerpt: "In his continuing effort to connect to a younger audience (like the time he went on 'Between Two Ferns'), President Barack Obama sat down with, and took questions, from three YouTube stars: GloZell Green (3 million followers), Bethany Mota (8 million followers) and half of the vlogbrothers (2.4 million followers).",

postTags: ['YouTube', 'interview', 'Obama', 'president']

},

// etc...

];

I need to get all values from every "postTags" array from this object (combine all arrays) and after that I need to remove all repeative values from it. As a result I need to extract all tags at once with non repeated values. I am digging in for loops but it's getting very complicated and my knowlage runs out at some point. Can you give me some suggestions about it? Thank you in advance!

(I am using it in Angularjs environment and I was trying nested ng-repeats and I hoped I will come up with something easy but no luck.)

网友答案:

Using jQuery (apply a different syntax as necessary):

var containerObject = {},
    finalArray = new Array();
$.each(PostsData, function(key, value) {
    $.each(value.postTags, function(key, value){
        containerObject[value] = true
    });
});
$.each(containerObject, function(key, value) {
    finalArray.push(key)
});
网友答案:

You could use Array.prototype.reduce and Array.protoype.forEach to build an array of unique tag values:

var uniqueTags = PostsData.reduce(function(allTags, post) {  
  post.postTags.forEach(function(tag) { 
    if(allPosts.indexOf(tag) === - 1) {
      allTags.push(tag)
    }
  }); 
  return allTags; 
}, []);

Or, if you can use underscore.js or lo-dash:

_.chain(PostsData).pluck('postTags').flatten().uniq().value()
相关阅读:
Top