过滤具有相同 id 的对象而不是 javascript .filter ()
2019-03-06
294
我需要在数组中创建一个过滤器,还需要一个计数器来知道有多少条记录具有相同的 id。我尝试使用过滤器,但没有成功,因为我不知道要将它与什么进行比较。这是一个学生名单,只有 3 个不同的学生,并且重复了几次,因为它是针对学生重复的药品清单。
var arr = [
{
"gl90Tabl": null,
"linkRece": "",
"co01Apme": 5359,
"co90Alun": 921,
"co00Apme": 281,
"dataApme": "2019-03-06",
"horaApme": "10:00",
"nomeApme": "Tylenol",
"dosaApme": "10 gotas",
"viadApme": "Oral",
"obsApme": "Aplicar mesmo que chore.",
"situApme": "PEND",
"dhapApme": null
},
{
"gl90Tabl": null,
"linkRece": "",
"co01Apme": 5360,
"co90Alun": 921,
"co00Apme": 281,
"dataApme": "2019-03-06",
"horaApme": "11:00",
"nomeApme": "Tylenol",
"dosaApme": "10 gotas",
"viadApme": "Oral",
"obsApme": "Aplicar mesmo que chore.",
"situApme": "PEND",
"dhapApme": null
},
{
"gl90Tabl": null,
"linkRece": "",
"co01Apme": 5361,
"co90Alun": 921,
"co00Apme": 281,
"dataApme": "2019-03-06",
"horaApme": "12:00",
"nomeApme": "Tylenol",
"dosaApme": "10 gotas",
"viadApme": "Oral",
"obsApme": "Aplicar mesmo que chore.",
"situApme": "PEND",
"dhapApme": null
},
{
"gl90Tabl": null,
"linkRece": "",
"co01Apme": 5362,
"co90Alun": 921,
"co00Apme": 281,
"dataApme": "2019-03-06",
"horaApme": "14:00",
"nomeApme": "Tylenol",
"dosaApme": "10 gotas",
"viadApme": "Oral",
"obsApme": "Aplicar mesmo que chore.",
"situApme": "PEND",
"dhapApme": null
},
{
"gl90Tabl": null,
"linkRece": "",
"co01Apme": 5363,
"co90Alun": 921,
"co00Apme": 281,
"dataApme": "2019-03-06",
"horaApme": "16:00",
"nomeApme": "Tylenol",
"dosaApme": "10 gotas",
"viadApme": "Oral",
"obsApme": "Aplicar mesmo que chore.",
"situApme": "PEND",
"dhapApme": null
},
{
"gl90Tabl": null,
"linkRece": "",
"co01Apme": 5340,
"co90Alun": 2601,
"co00Apme": 279,
"dataApme": "2019-03-06",
"horaApme": "16:00",
"nomeApme": "Aspirina",
"dosaApme": "10 Gotas",
"viadApme": "Oral",
"obsApme": "Aplicar mesmo que chore",
"situApme": "PEND",
"dhapApme": null
},
{
"gl90Tabl": null,
"linkRece": "",
"co01Apme": 5357,
"co90Alun": 455,
"co00Apme": 280,
"dataApme": "2019-03-06",
"horaApme": "22:00",
"nomeApme": "Dipirona",
"dosaApme": "10ml",
"viadApme": "Oral",
"obsApme": "",
"situApme": "PEND",
"dhapApme": null
},
{
"gl90Tabl": null,
"linkRece": "",
"co01Apme": 5358,
"co90Alun": 455,
"co00Apme": 280,
"dataApme": "2019-03-06",
"horaApme": "23:00",
"nomeApme": "Dipirona",
"dosaApme": "10ml",
"viadApme": "Oral",
"obsApme": "",
"situApme": "PEND",
"dhapApme": null
}
]
console.log(arr)
1个回答
要计算某些属性相同的次数,您可以循环遍历数组并执行以下操作:
let arr = [
{
id: 1,
name: "Joe"
},
{
id: 1,
name: "Joe"
},
{
id: 2,
name: "Mary"
}
];
let idCounts = {};
const propertyToCount = 'id';
for (let i = 0; i < arr.length; i++) {
const elem = arr[i];
if(typeof idCounts[elem[propertyToCount]] === 'undefined') {
idCounts[elem[propertyToCount]] = 1;
}
else {
idCounts[elem[propertyToCount]] = idCounts[elem[propertyToCount]] + 1;
}
}
我希望我正确理解了这个问题。
Morten Twellmann
2019-03-06