简体   繁体   English

如何使用JavaScript从对象中删除重复项

[英]How to remove duplicates from object using javascript

My object is like this. 我的对象就是这样。

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

and the expected result is: 预期结果是:

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

How to achieve this using javascript? 如何使用javascript做到这一点?

You can try this, with your current structure, where each object in the myData array has only one member. 您可以使用当前结构尝试此操作,其中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)); 

You can use this code: 您可以使用以下代码:

 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); 

First use reduce function to create an object then loop over it & in new array push the value 首先使用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