亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從對象數組中刪除重復項

從對象數組中刪除重復項

天涯盡頭無女友 2023-03-10 13:55:56
嗨,我正在嘗試使用 id 從對象數組中刪除重復項,但 id 為 null 那么該對象應包含那些 null id 并刪除其他重復項這是對象數組示例:const arr = [  {    id: 6652,    value: "erger"  },  {    id: 6652,    value: "sdfs"  },  {    id: 6653,    value: "sdgdfg"  },  {    id: 6000,    value: "trgd"  },  {    id: 6667,    value: "asdf"  },  {    id: 6667,    value: "fdg"  },  {    id: 6668,    value: "dfgr"  },  {    id: null,    value: "fg"  },  {    id: null,    value: "dfgdf"  },  {    id: null,    value: "fg"  },  {    id: null,    value: "dfgdf"  }];下面是最終結果array = [{    id: 6652    value: "sdfs"  },  {    id: 6653    value: "sdgdfg"  },  {    id: 6000    value: "trgd"  },  {    id: 6667    value: "fdg"  },  {    id: 6668    value: "dfgr"  },  {    id: null    value: "fg"  },  {    id: null    value: "dfgdf"  },  {    id: null    value: "fg"  },  {    id: null    value: "dfgdf"  }]在上面的結果中,刪除了 6652 和 6667,因為它們是重復的,但是保留了空 ID,因為我不想刪除空 ID 并刪除其他重復值。下面是我正在嘗試使用的邏輯,但如果 id 為 null,它就不起作用array= array.filter((v,i,a)=>a.findIndex(t=>( v.id !== null && t.id === v.id ))===i)
查看完整描述

3 回答

?
MM們

TA貢獻1886條經驗 獲得超2個贊

const filterKeys = {};

const filtered = arr.reduce((acc, item) => {

  if (item.id === null || !(item.id in filterKeys)) {

    filterKeys[item.id] = true;

    acc.push(item);

  }


  return acc;

}, []);

在這種情況下,創建一個單獨的對象來跟蹤遇到的對象 ID filterKeys。


因為array是一個數組,所以做一個 reduce 來遍歷數組。如果id為 nuil 或未在 中找到filterKeys,則將該項目推入累加器并將其返回以用于下一次迭代。由于我們不關心為 null 的 id,因此它們沒有效果,因此不會被過濾掉。


查看完整回答
反對 回復 2023-03-10
?
慕標琳琳

TA貢獻1830條經驗 獲得超9個贊

使用下面的代碼,我用你的對象數組測試(工作):


    arr.forEach(function (item) {


        if (item.id == null) {

            result.push(item);

        }

        else {

            var index = result.findIndex(x => x.id == item.id);

            if (index == -1)

            {

                result.push(item);

            }

           

        }

    });

    console.log(result)


查看完整回答
反對 回復 2023-03-10
?
慕后森

TA貢獻1802條經驗 獲得超5個贊

你可以試試這個 -


const array = [{ id: 6652, value: 'erger' },{ id: 6652, value: 'sdfs' },{ id: 6653, value: 'sdgdfg' },{ id: 6000, value: 'trgd' },{ id: 6667, value: 'asdf' },{ id: 6667, value: 'fdg' },{ id: 6668, value: 'dfgr' },{ id: null, value: 'fg' },{ id: null, value: 'dfgdf' },{ id: null, value: 'fg' },{ id: null, value: 'dfgdf' },];

let index = 0;

const result = Object.values(

    array.reduce(

        (acc, curr) =>

            curr.id === null ? { ...acc, [index++]: curr } : { ...acc, [curr.id]: curr },

        {}

    )

);


console.log(result);

.as-console-wrapper {min-height: 100%; top: 0}


查看完整回答
反對 回復 2023-03-10
  • 3 回答
  • 0 關注
  • 158 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號