我的重复 json 数组如下所示:
var list = [
{"id":"123","class": "Math K", "subject": "Counting & Cardinality"},
{"id":"124","class": "Math K", "subject": "Counting & Cardinality"},
{"id":"125","class": "Math K", "subject": "Counting & Cardinality"},
{"id":"126","class": "Math K", "subject": "Counting & Cardinality"},
{"id":"127","class": "Math K", "subject": "Geometry"},
{"id":"128","class": "Math 1", "subject": "Counting & Cardinality"},
{"id":"129","class": "Math 1", "subject": "Counting & Cardinality"},
{"id":"120","class": "Math 1", "subject": "Orders of Operation"},
{"id":"121","class": "Math 2", "subject": "Geometry"},
{"id":"122","class": "Math 2", "subject": "Geometry"}
];
我需要删除具有相同类和主题的重复项(例如 Math K 和 Counting & Cardinality 或 Math 2 和 Geometry),但保留第一条记录的 ID,因此它应该如下所示:
var newList = [
{"id":"123","class": "Math K", "subject": "Counting & Cardinality"},
{"id":"127","class": "Math K", "subject": "Geometry"},
{"id":"128","class": "Math 1", "subject": "Counting & Cardinality"},
{"id":"120","class": "Math 1", "subject": "Orders of Operation"},
{"id":"121","class": "Math 2", "subject": "Geometry"},
];
我试过这个代码:
var newList = [];
for( var class in list ) {
for( var subject in list[class] ) {
outputList.push({ id: id, class: class, subject: subject });
}
}
JSON.stringify( newList, null, 4 );
但它并没有带来结果。我非常感谢您帮助调整我的代码。谢谢你。
另一种方法是使用reduce() 删除重复项。
该list.reduce()
收益与密钥的对象${b.class}_${b.subject}
,并与价值观object
的样子如下:
{
"Math K_Counting & Cardinality": {
"id": "123",
"class": "Math K",
"subject": "Counting & Cardinality"
},
"Math K_Geometry": { "id": "127", "class": "Math K", "subject": "Geometry" },
"Math 1_Counting & Cardinality": {
"id": "128",
"class": "Math 1",
"subject": "Counting & Cardinality"
},
"Math 1_Orders of Operation": {
"id": "120",
"class": "Math 1",
"subject": "Orders of Operation"
},
"Math 2_Geometry": { "id": "121", "class": "Math 2", "subject": "Geometry" }
}
然后提取 的值list.reduce()
以得到结果Object.values()
const list = [
{ id: "123", class: "Math K", subject: "Counting & Cardinality" },
{ id: "124", class: "Math K", subject: "Counting & Cardinality" },
{ id: "125", class: "Math K", subject: "Counting & Cardinality" },
{ id: "126", class: "Math K", subject: "Counting & Cardinality" },
{ id: "127", class: "Math K", subject: "Geometry" },
{ id: "128", class: "Math 1", subject: "Counting & Cardinality" },
{ id: "129", class: "Math 1", subject: "Counting & Cardinality" },
{ id: "120", class: "Math 1", subject: "Orders of Operation" },
{ id: "121", class: "Math 2", subject: "Geometry" },
{ id: "122", class: "Math 2", subject: "Geometry" },
];
const output = Object.values(
list.reduce((acc, b) => {
if (!acc[`${b.class}_${b.subject}`]) acc[`${b.class}_${b.subject}`] = b;
return acc;
}, {})
);
console.log(output);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句