Javascript / jQuery检查对象中的重复值

时间:2013-12-05 22:56:00

标签: javascript jquery json

我有一个对象数组,它有一个'轨道'数组。我想要做的是比较所有轨道对象的mbid值,检查是否有任何重复项,并将重复的轨道对象存储到新的数组中。任何帮助或指导?

[
  {
    "track": [
      {
        "name": "Radiapathy",
        "mbid": "4c0767f1-1c2e-4790-a8d1-ee7f78f0ac84",
        "url": "http://www.last.fm/music/The+Velvet+Teen/_/Radiapathy"
      },
      {
        "name": "How Did I Get Here",
        "mbid": "64b3078f-89cd-4ad5-bc7a-b43af082b00f",
        "url": "http://www.last.fm/music/Odesza/_/How+Did+I+Get+Here"
      },
      {
        "name": "Sunshine Roof",
        "mbid": "837db975-c93e-45ca-992c-0c924ef0f34f",
        "url": "http://www.last.fm/music/The+Innocence+Mission/_/Sunshine+Roof"
      }
    ]
  },
  {
    "track": [
      {
        "name": "Traveling",
        "mbid": "b40c24b8-3295-4219-af59-855b69958ca2",
        "url": "http://www.last.fm/music/Tennis/_/Traveling"
      },
      {
        "name": "Ghost",
        "mbid": "6273ae8f-3d2c-44c6-8c0d-53013ba79b4e",
        "url": "http://www.last.fm/music/Neutral+Milk+Hotel/_/Ghost"
      },
      {
        "name": "Strange",
        "mbid": "5a015df2-6c4a-4192-bea8-14ec5f297713",
        "url": "http://www.last.fm/music/Built+to+Spill/_/Strange"
      }
    ]
  },
  {
    "track": [
      {
        "name": "Radiapathy",
        "mbid": "4c0767f1-1c2e-4790-a8d1-ee7f78f0ac84",
        "url": "http://www.last.fm/music/The+Velvet+Teen/_/Radiapathy"
      },
      {
        "name": "Let Me Show You Love",
        "mbid": "",
        "url": "http://www.last.fm/music/Cut+Copy/_/Let+Me+Show+You+Love"
      },
      {
        "name": "Footsteps",
        "mbid": "",
        "url": "http://www.last.fm/music/Cut+Copy/_/Footsteps"
      }
    ]
  }
] 

1 个答案:

答案 0 :(得分:3)

这个问题的答案(Elminating duplicates in a JSON object)几乎可以回答你的问题。我已经使用了这个(“智能(呃)”方式)并进行了修改,以适应您的阵列和放大器要求:

var key = null;
var noDupes = [];
var dupes = [];
for (var i = 0; i < arr.length; i++)
{
    // loop through each track:
    for (var j = 0; j < arr[i].track.length; j++)
    {
        key = arr[i].track[j].mbid;
        if (!hash.contains(key))
        {
            hash.add(key);
            noDupes.push(arr[i].track[j]); // if not duplicate
        }
        else
        {
            dupes.push(arr[i].track[j]); // if duplicate
        }
    }
}

http://jsfiddle.net/6wspy/