【问题标题】:Filtering JavaScript array of objects by property of an object and removing duplicates按对象的属性过滤对象的 JavaScript 数组并删除重复项
【发布时间】:2013-09-06 20:01:32
【问题描述】:

我有一个对象数组

[
{"title": "video01", "src":"/embed/video1","hero":"hero1"},    
{"title": "video02", "src":"/embed/video2","hero":"hero1"},    
{"title": "video03", "src":"/embed/video3","hero":"hero1"},    
{"title": "video04", "src":"/embed/video4","hero":"hero2"},    
{"title": "video05", "src":"/embed/video5","hero":"hero2"},    
{"title": "video06", "src":"/embed/video6","hero":"hero3"},    
{"title": "video07", "src":"/embed/video7","hero":"hero3"},    
{"title": "video08", "src":"/embed/video8","hero":"hero3"}]

我需要返回 [hero1, hero2, hero3] 最好的方法是什么?

感谢大家的帮助

【问题讨论】:

  • 你有没有尝试过?
  • 嘿,是的,我已经完成了将值分配给 Array 的迭代,然后删除了又长又丑的重复项。我可能正在寻找 undescore 解决方案
  • 请发布任何您已经尝试过的内容并描述您遇到的困难。

标签: javascript arrays duplicates filtering


【解决方案1】:

这里已经讨论过从数组中删除重复项:Unique values in an array

如果您可以访问Array.prototype.indexOf,则检查重复项很容易(FF、Chrome、Opera 和 IE >= 9,请参阅compatibility table):

var heroes = [];
for (var i = 0 ; i < myArray.length ; i++) {
    var heroName = myArray[i].hero;
    if (heroes.indexOf(heroName) == -1) {
        heroes.push(heroName);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-14
    • 1970-01-01
    • 1970-01-01
    • 2018-07-29
    • 2022-08-18
    • 2019-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多