json数据检查是否重复相同的ID [英] json data check if same id repeat
本文介绍了json数据检查是否重复相同的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个json数据,其中一个id具有不同的color_id. 所以从那里我只想检查是否重复相同的ID,然后只保留第一个
I have a json data there one id has different color_id. So from there I just want to check if same id repeat then just keep first one
这是我的示例JSON
Here is my sample 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" }];
我尝试过reduce,但是我发现在那里修改了数据结构,所以我不确定是否会得到所需的输出.
I tried reduce but there I found that modify data structure so I am not sure that I will get my desired output or not.
推荐答案
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 )
说明:
- 您创建了一个用于存储ID的地图.
- 然后过滤数组,每次我们找到不在地图中的条目时,都会将其添加到列表中并返回true.如果我们已经在列表中添加了它,则返回false以丢弃该条目.
条件的最后一部分使用赋值返回赋值的事实.
the last part of the conditional is using the fact that an assignment returns the assigned value.
这篇关于json数据检查是否重复相同的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文