gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:05:27 25 4
gpt4 key购买 nike

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

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”数组中获取所有值(合并所有数组),然后我需要从中删除所有重复值。因此,我需要一次提取所有具有非重复值的标签。我正在研究 for 循环,但它变得非常复杂,我的知识有时会耗尽。你能给我一些建议吗?提前致谢!

(我在 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;
}, []);

或者,如果您可以使用 underscore.js 或 lo-dash:

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

关于JavaScript for in - 从主对象获取、合并和处理数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28126394/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com