猿问

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

我想检查我的数组中是否有具有匹配值的对象,如果它们匹配,则删除具有最低索引的对象,因为该对象将是“较旧的”


我成功地使用这种方法删除了数组中的重复对象,但是当我获得这些对象的特定值时,我不确定


someFunction() {

  let cart = this.state.currentUser.cart

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

      return index === cart.findIndex(obj => {

          obj.use === light.use

      })

    })

  cart = newCartArray

}


万千封印
浏览 139回答 3
3回答

胡说叔叔

您可以使用 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; }

繁花不似锦

let cart = this.state.currentUser.cart;let index = cart.indexOf(light);if( index != -1) {&nbsp; &nbsp; cart.splice( index,1);}或者如果您需要检查 .uselet cart = this.state.currentUser.cart;for( let i =0; i < cart.length; i++) {&nbsp; &nbsp; if( cart[i].use === light.use) {&nbsp; &nbsp; &nbsp; &nbsp; cart.splice(i,1);&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }}

青春有我

这应该有效:someFunction() {&nbsp; let cart = this.state.currentUser.cart&nbsp; &nbsp; const newCartArray = cart.filter((light, index) => {&nbsp; &nbsp; &nbsp; return cart.slice(index + 1).findIndex(obj => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; obj.use === light.use&nbsp; &nbsp; &nbsp; }) === -1;&nbsp; &nbsp; })&nbsp; cart = newCartArray}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答