根据2键从数组中删除重复的对象

时间:2019-12-10 06:59:21

标签: javascript ecmascript-6 ecmascript-5 ecmascript-7

我有这样的对象数组,我想根据2键删除重复的项目, 在我的数据中,我想删除具有相同的room_idmdate的项目, 在下面的代码对象4和5中,具有相同的room_id和mdate,因此我应该删除其中之一,任何解决方案吗?

我具有删除重复对象的功能,但可以检查一个键

function getUnique(arr, comp) {

    arr.map()
    const unique = arr
        .map(e => e[comp])

        // store the keys of the unique objects
        .map((e, i, final) => final.indexOf(e) === i && i)

        // eliminate the dead keys & store unique objects
        .filter(e => arr[e])
        .map(e => arr[e]);

    return unique;
}



arr = [{
cond: 2
extra_fee: 20000
kind: ""
mdate: "2019-12-15"
price: "100000"
room_id: 1
},
{
cond: 2
extra_fee: 20000
kind: ""
mdate: "2019-12-10"
price: "100000"
room_id: 1
},
{
cond: 2
extra_fee: 20000
kind: ""                       object 3 <--------------   is same - have same mdate and room_id
mdate: "2019-12-10"
price: "100000"
room_id: 2
},
{
cond: 2
extra_fee: 20000
kind: ""
mdate: "2019-12-10"
price: "100000"
room_id: 2                       object 4 <--------------   are same - have same mdate and room_id
},
{
cond: 2
extra_fee: 20000
kind: ""
mdate: "2019-12-10"
price: "100000"
room_id: 7
}
]

2 个答案:

答案 0 :(得分:1)

这将删除重复项,

  let arr = [{
    cond: 2,
    extra_fee: 20000,
    kind: "",
    mdate: "2019-12-15",
    price: "100000",
    room_id: 1
  },
  {
    cond: 2,
    extra_fee: 20000,
    kind: "",
    mdate: "2019-12-10",
    price: "100000",
    room_id: 1
  },
  {
    cond: 2,
    extra_fee: 20000,
    kind: "",
    mdate: "2019-12-10",
    price: "100000",
    room_id: 2
  },
  {
    cond: 2,
    extra_fee: 20000,
    kind: "",
    mdate: "2019-12-10",
    price: "100000",
    room_id: 2
  },
  {
    cond: 2,
    extra_fee: 20000,
    kind: "",
    mdate: "2019-12-10",
    price: "100000",
    room_id: 7
  }
  ]
  
const arrayWithoutDuplicates = arr.filter((v,i,a)=>a.findIndex(t=>(t.room_id=== v.room_id && t.mdate===v.mdate))===i)
console.log(arrayWithoutDuplicates)

答案 1 :(得分:0)

尝试一下:

function getUnique(arr, comp) {
    let tmpObj = {};
    let unique = [];
    for (let i = 0; i < arr.length; i++) {
      if (tmpObj[arr[i][comp]] === undefined) {
        tmpObj[arr[i][comp]] = arr[i][comp];
        unique.push(arr[i]);
      }
    }
    return unique;
  }

  let arr = [{
    cond: 2,
    extra_fee: 20000,
    kind: "",
    mdate: "2019-12-15",
    price: "100000",
    room_id: 1
  },
  {
    cond: 2,
    extra_fee: 20000,
    kind: "",
    mdate: "2019-12-10",
    price: "100000",
    room_id: 1
  },
  {
    cond: 2,
    extra_fee: 20000,
    kind: "",
    mdate: "2019-12-10",
    price: "100000",
    room_id: 2
  },
  {
    cond: 2,
    extra_fee: 20000,
    kind: "",
    mdate: "2019-12-10",
    price: "100000",
    room_id: 2
  },
  {
    cond: 2,
    extra_fee: 20000,
    kind: "",
    mdate: "2019-12-10",
    price: "100000",
    room_id: 7
  }
  ]
  console.log(getUnique(arr, "room_id"));