JavaScript for in - 从主对象获取、组合和处理数组
JavaScript for in - get, combine and process arrays from the main object
我有一个具有以下结构的对象:
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.reduce
和Array.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)
});
相关文章:
- 可以't让我的if语句处理js中的html表单输入
- keyup事件处理程序更改焦点不适用于快速键入
- 如何使用jquery处理php循环通过元素
- angular.js没有'无法在PhoneGap中处理视图标记
- 根据id将json数组组合为一个json数组
- Webpack/Rect:遵循egghead.io教程,但出现错误:您可能需要一个合适的加载程序来处理此文件类型
- 提示使用服务器端事件处理程序激活JavaScript
- JavaScript for in - 从主对象获取、组合和处理数组
- 将图像组合在一起并在窗口加载时对图像进行动画处理
- 如何组合类似的事件处理程序
- 在jQuery中组合对事件处理程序的操作
- 在不同的 DOM 元素中组合/批处理多个 CSS 更新以减少重排/重绘
- 将点击处理程序与CSS同级选择器组合时,IE中的奇怪行为
- 处理组合键盘快捷键
- 组合多个API调用和处理后从工厂方法返回promise
- jQuery Validate将错误作为单独的实例处理,而不是将它们组合在一起
- .off() / .on() jQuery事件处理绑定组合的效率
- 如何记录/使用硒处理组合框和选择dijit使用的项目
- 如何同时组合所有事件处理程序
- 在Extjs中,需要一个全局组合框类来处理不同json数据的不同实例