簡體   English   中英

如何使用JavaScript從對象中刪除重復項

[英]How to remove duplicates from object using javascript

我的對象就是這樣。

var myData = [
   { 123: 1}, 
   { 123: 2}, 
   { 124: 3}, 
   { 124: 4}
];

預期結果是:

var myDataNew = [
    {123: [1, 2]}, 
    {124: [3,4]}
];

如何使用javascript做到這一點?

您可以使用當前結構嘗試此操作,其中myData數組中的每個對象只有一個成員。

 const myData = [ { 123: 1}, { 123: 2}, { 124: 3}, { 124: 4} ]; const groupDuplicates = (arr) => arr.reduce((acc, val) => { const key = Object.keys(val).toString(); const item = acc.find((item) => Object.keys(item).toString() === key); if (!item) acc.push({ [key]: [val[key]]}); else item[key].push(val[key]); return acc; }, []); console.log(groupDuplicates(myData)); 

您可以使用以下代碼:

 var myData = [ { 123: 1}, { 123: 2}, { 124: 3}, { 124: 4} ]; /* var myDataNew = [ {123: [1, 2]}, {124: [3,4]} ]; */ var keys = myData.map(current=>Object.keys(current)[0]); //console.log(keys);//(4) ["123", "123", "124", "124"] var result = []; keys.forEach((current,index)=>{ //findIndex in result let id = result.findIndex(c=>{ if(c[current]) return c; }); // not find if(id===-1){ let obj = {}; obj[current] = [myData[index][current]]; result.push(obj); // find, let push }else{ result[id][current].push(myData[index][current]); } }); console.log(result); 

首先使用reduce函數創建一個對象,然后在其上循環並在新數組中推送該值

 var myData = [{ 123: 1 }, { 123: 2 }, { 124: 3 }, { 124: 4 } ]; let k = myData.reduce(function(acc, curr) { let getKey = Object.keys(curr)[0];// get the key let getVal = Object.values(curr)[0] //get the value //check if key like 123,124 exist in object if (!acc.hasOwnProperty(getKey)) { acc[getKey] = [getVal] } else { acc[getKey].push(getVal) } return acc; }, {}) let newArray = []; for (let keys in k) { newArray.push({ [keys]: k[keys] }) } console.log(newArray) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM