I have an array called items
, here is a sampel of the data inside the array:
[
{
"id":"123",
"key":"[email protected]",
"status":"attempted"
},
{
"id":"123",
"key":"[email protected]",
"status":"waiting"
},
{
"id":"123",
"key":"[email protected]",
"status":"completed"
},
{
"id":"123",
"key":"[email protected]",
"status":"completed"
},
{
"id":"456",
"key":"[email protected]",
"status":"waiting"
},
{
"id":"456",
"key":"[email protected]",
"status":"attempted"
},
{
"id":"456",
"key":"[email protected]",
"status":"failed"
},
{
"id":"456",
"key":"[email protected]",
"status":"attempted"
},
{
"id":"456",
"key":"[email protected]",
"status":"waiting"
}
]
I would like to group and filter items from my array. I have figured out that I could create a second array and push all items that match my criteria into that second array, but unsure how to achieve this.
Here are the criteria for grouping and filtering:
- Group by
id
andkey
so that all records with the sameid
andkey
are grouped together and can be filtered in the next step. So here I could dynamically create arrays and they would look like this:
Array 1:
[
{
"id":"123",
"key":"[email protected]",
"status":"attempted"
},
{
"id":"123",
"key":"[email protected]",
"status":"waiting"
},
{
"id":"123",
"key":"[email protected]",
"status":"completed"
}
]
Array 2:
[
{
"id":"123",
"key":"[email protected]",
"status":"completed"
}
]
Array 3:
[
{
"id":"456",
"key":"[email protected]",
"status":"waiting"
}
]
Array 4:
[
{
"id":"456",
"key":"[email protected]",
"status":"attempted"
},
{
"id":"456",
"key":"[email protected]",
"status":"failed"
}
]
Array 5:
[
{
"id":"456",
"key":"[email protected]",
"status":"attempted"
},
{
"id":"456",
"key":"[email protected]",
"status":"waiting"
}
]
- Above arrays should be filtered by
status
: if in an array I have either statusesfailed
orcompleted
I do not want to consider this array anymore. Data from arrays that qualify could be pushed to my final array and I just need theid
andkey
filed, I don't need to see the different statuses:
Final array:
[
{
"id":"456",
"key":"[email protected]"
},
{
"id":"456",
"key":"[email protected]"
}
]
So far I have tried this, but I am unable to get the desired results:
if(items.length >= 1) {
for (i = 0; i < items.length; i++) {
key = items[i]["key"];
status = items[i]["status"];
id = items[i]["id"];
var arr=[];
if(items[i]["key"]==key && items[i]["id"]==id) {
arr.push(items[i]["key"])
arr.push(items[i]["id"])
}
}
Any help would be appreciated.
You could group, filter and map the arrays with array with objects without
status
.In really old JS