Javascript:使用单个属性删除对象数组中的重复项 [英] Javascript: Remove duplicates in array of objects using a single property

查看:46
本文介绍了Javascript:使用单个属性删除对象数组中的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的对象,其中"id"是唯一的.我需要从小于ES5的任何版本的JavaScript中的对象数组中删除重复项.我需要根据id字段进行比较,并删除其重复项.

I have object like this where 'id', is unique. I need to remove duplicates from the array of objects in javascript in any version less than ES5. I need to compare based on the id field and remove its duplicates.

示例:

Object = [
{id: id_one, value: value_one, label: ABC},
{id: id_one, value: value_one, label: ABC},
{id: id_three, value: value_three, label: ABX},
{id: id_two, value: value_two, label: ABY},
{id: id_four, value: value_four, label: ABD}
];

输出:

result = [
{id: id_one, value: value_one, label: ABC},
{id: id_three, value: value_three, label: ABX},
{id: id_two, value: value_two, label: ABY},
{id: id_four, value: value_four, label: ABD}
];

我尝试过这样的逻辑

function getDistValues(object) {
  var distObject = [];
  var tempIndex = [];
  var length = object.length;

  for (var i = 0; i < length; i++) {
    tempIndex.push(object[i].id);

    if (tempIndex.indexOf(object[i].id) === -1 || i === 0) {
      distObject.push(object[i]);
    }
  }

  return distObject;
}

它仅给出第一个对象.我尝试过映射ID并进行比较,但没有用.

It is only giving the first object. I tried like mapping the ids and comparing it but not worked.

任何帮助对我都会有用.

Any help will be useful to me.

推荐答案

这是因为您总是将ID添加到 tempIndex 数组中,因此它始终认为当前的ID是重复的.试试:

It's because you are always adding the id to the tempIndex array, so it always thinks the current one is a duplicate. Try:

function getDistValues(object) {
  var distObject = [];
  var tempIndex = [];
  var length = object.length;

  for (var i = 0; i < length; i++) {    
    if (tempIndex.indexOf(object[i].id) === -1 || i === 0) {
      tempIndex.push(object[i].id);
      distObject.push(object[i]);
    }
  }

  return distObject;
}

这篇关于Javascript:使用单个属性删除对象数组中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆