从javascript的多维数组对象中删除重复的值



这是我的javascript数组:

 [{
     "id": "44",
     "name": "chathura"
 }, {
     "id": "45",
     "name": "gayan"
 }, {
     "id": "48",
     "name": "sunimal"
 }, {
     "id": "47",
     "name": "chathura"
 }, {
     "id": "20",
     "name": "yasith"
 }, {
     "id": "21",
     "name": "thisaru"
 }, {
     "id": "42",
     "name": "insaf"
 }, {
     "id": "63",
     "name": "sunimal"
 }, {
     "id": "78",
     "name": "yasith"
 }, {
     "id": "36",
     "name": "thisaru"
 }]

我想从这个数组中删除重复的名称现有对象元素,并得到以下内容:

[{
    "id": "47",
    "name": "chathura"
}, {
    "id": "45",
    "name": "gayan"
}, {
    "id": "48",
    "name": "sunimal"
}, {
    "id ": "20",
    "name ": "yasith "
}, {
    "id ": "21 ",
    "name ": "thisaru"
}, {
    "id ": "42 ",
    "name ": "insaf"
}]

如何删除重复项?

您可以遍历数组并使用散列表过滤已使用的任何id:

function getUniqueNames(nameObjects) {
  var existingIds = { };
  return nameObjects
    .filter(function(nameObject) {
      var id = nameObject.id;
      var alreadyExists = existingIds[id];
      existingIds[id] = true;
      return alreadyExists;
    });

我不确定您的用例,但在您的情况下,将数据转换为Map可能是有意义的。映射的工作原理类似于散列表,并将每个名称映射到其ID。它们通过设计强制唯一性:

var names = nameObjects
  .reduce(function(map, nameObject) {
    map.set(nameObject.id, nameObject.name);
    return map;
  }, new Map());
// Look up a name by ID
names.get(47);
// Do something for every name
names.forEach(function(name, key) {
  console.info(name, 'has ID', key);
});

地图是ES6的,你可能需要在一些浏览器中使用polyfill

使用push方法试试这个有效的解决方案:

JS:

var arr = {};
for ( var i=0; i < x.length; i++ )
    arr[x[i]['name']] = x[i];
var result = new Array();
for ( var key in arr )
    result.push(arr[key]);

返回一个包含非重复对象的对象数组result

结果:

[{
    "id": "47",
    "name": "chathura"
}, {
    "id": "45",
    "name": "gayan"
}, {
    "id": "48",
    "name": "sunimal"
}, {
    "id ": "20",
    "name ": "yasith "
}, {
    "id ": "21 ",
    "name ": "thisaru"
}, {
    "id ": "42 ",
    "name ": "insaf"
}]

相关内容

  • 没有找到相关文章

最新更新