为了账号安全,请及时绑定邮箱和手机立即绑定

如何删除具有匹配值的对象数组中的对象

如何删除具有匹配值的对象数组中的对象

万千封印 2021-11-18 09:39:32
我想检查我的数组中是否有具有匹配值的对象,如果它们匹配,则删除具有最低索引的对象,因为该对象将是“较旧的”我成功地使用这种方法删除了数组中的重复对象,但是当我获得这些对象的特定值时,我不确定someFunction() {  let cart = this.state.currentUser.cart    const newCartArray = cart.filter((light, index) => {      return index === cart.findIndex(obj => {          obj.use === light.use      })    })  cart = newCartArray}
查看完整描述

3 回答

?
胡说叔叔

TA贡献1804条经验 获得超8个赞

您可以使用 aMap并使用想要的键存储最后一个对象,然后仅获取最后存储的对象。


var array = [{ id: 1, index: 0 }, { id: 2, index: 1 }, { id: 3, index: 2 }, { id: 2, index: 3 }, { id: 3, index: 4 }, { id: 1, index: 5 }, { id: 4, index: 6 }, { id: 5, index: 7 }],

    result = Array.from(array.reduce((m, o) => m.set(o.id, o), new Map).values());


console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


如果你想保持原来的顺序,你可以检查相同的对象引用进行过滤。


var array = [{ id: 1, index: 0 }, { id: 2, index: 1 }, { id: 3, index: 2 }, { id: 2, index: 3 }, { id: 3, index: 4 }, { id: 1, index: 5 }, { id: 4, index: 6 }, { id: 5, index: 7 }],

    map = array.reduce((m, o) => m.set(o.id, o), new Map),

    result = array.filter(o => o === map.get(o.id));


console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


查看完整回答
反对 回复 2021-11-18
?
繁花不似锦

TA贡献1851条经验 获得超4个赞

let cart = this.state.currentUser.cart;

let index = cart.indexOf(light);

if( index != -1) {

    cart.splice( index,1);

}


或者如果您需要检查 .use


let cart = this.state.currentUser.cart;

for( let i =0; i < cart.length; i++) {

    if( cart[i].use === light.use) {

        cart.splice(i,1);

        break;

    }

}


查看完整回答
反对 回复 2021-11-18
?
青春有我

TA贡献1784条经验 获得超8个赞

这应该有效:


someFunction() {

  let cart = this.state.currentUser.cart

    const newCartArray = cart.filter((light, index) => {

      return cart.slice(index + 1).findIndex(obj => {

          obj.use === light.use

      }) === -1;

    })

  cart = newCartArray

}


查看完整回答
反对 回复 2021-11-18
  • 3 回答
  • 0 关注
  • 138 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信