JavaScript for in - 从主对象获取、组合和处理数组

JavaScript for in - get, combine and process arrays from the main object

本文关键字:组合 处理 数组 获取 对象 in for JavaScript      更新时间:2023-09-26

我有一个具有以下结构的对象:

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...
            ];

我需要从这个对象获取每个"postTags"数组的所有值(合并所有数组),然后我需要从中删除所有重复值。因此,我需要一次提取具有非重复值的所有标签。我正在挖掘循环,但它变得非常复杂,我的知识在某个时候耗尽。你能给我一些建议吗?提前谢谢你!

(我在 Angularjs 环境中使用它,我正在尝试嵌套的 ng-repeats,我希望我能想出一些简单的东西,但没有运气。

您可以使用

Array.prototype.reduceArray.protoype.forEach来构建唯一标签值数组:

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

或者,如果您可以使用下划线.js或短划线:

_.chain(PostsData).pluck('postTags').flatten().uniq().value()

使用 jQuery(根据需要应用不同的语法):

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