json数据检查是否重复相同的id

我有一个json数据,其中一个id有不同的color_id。 所以从那里我只想检查同一个id是否重复然后只保留第一个

这是我的示例JSON

var data= [{ "id": "1", "name": "xxx", "age": "22","color_id": "22" }, { "id": "1", "name": "yyy", "age": "15","color_id": "1" }, { "id": "5", "name": "zzz", "age": "59","color_id": "22" }]; 

我想要的输出

 var data= [{ "id": "1", "name": "xxx", "age": "22","color_id": "22" }, { "id": "5", "name": "zzz", "age": "59","color_id": "22" }]; 

我尝试减少但在那里我发现修改数据结构所以我不确定我是否会得到我想要的输出。

 var data = [{ "id": "1", "name": "xxx", "age": "22", "color_id": "22" }, { "id": "1", "name": "yyy", "age": "15", "color_id": "1" }, { "id": "5", "name": "zzz", "age": "59", "color_id": "22" } ]; let map = {}; let uniqueEntries = data.filter((el) => map[el.id] ? false : map[el.id] = true); console.log(uniqueEntries ) 

您可以使用reduce创建一个新数组,在这个新数组中使用findIndex来检查这个新数组是否有一个具有相同id的对象。 如果存在具有相同id的对象,则不要推送具有相同id的另一个对象

 var data = [{ "id": "1", "name": "xxx", "age": "22", "color_id": "22" }, { "id": "1", "name": "yyy", "age": "15", "color_id": "1" }, { "id": "5", "name": "zzz", "age": "59", "color_id": "22" } ]; let m = data.reduce(function(acc, curr) { let findIndex = acc.findIndex(function(item) { return item.id === curr.id }) if (findIndex === -1) { acc.push(curr) } return acc; }, []) console.log(m) 

使用Array.reduceArray.some

 const data = [{ id: '1', name: 'xxx', age: '22', color_id: '22', }, { id: '1', name: 'yyy', age: '15', color_id: '1', }, { id: '5', name: 'zzz', age: '59', color_id: '22', }, ]; const reduced = data.reduce((tmp, x) => { if (tmp.some(y => y.id === x.id)) return tmp; return [ ...tmp, x, ]; }, []); console.log(reduced); 

您可以使用Set来跟踪已处理的ID。

 const // The data set with non-unique IDs data= [{ "id": "1", "name": "xxx", "age": "22","color_id": "22" }, { "id": "1", "name": "yyy", "age": "15","color_id": "1" }, { "id": "5", "name": "zzz", "age": "59","color_id": "22" }]; function dedupe(items) { // Create a set to keep track of IDs already encountered. const idSet = new Set(); // Filter the items, when an ID isn't in the set add it to the set and return true // so item is in the result array. When the ID is in the set return false so the // item will be dropped. return items.filter(item => { // If the ID is already in the set, drop it from the result. This way only the // first item with an ID is added to the result. if (idSet.has(item.id)) { return false; } // Add the ID to the set, this way we keep track of the IDs already encountered. idSet.add(item.id); // Return true so the item is included in the result array. return true; }); } console.log(dedupe(data));