I've an array of objects and I need to find objects with some property.
My array:
[
{
"lineItems": [
{
"id": "92477254-088f-4b6d-bb87-ba670b427eec",
"distributionChannel": {
"id": "9c5b1a2a-52dd-4cef-b914-94d2332c5c4f",
"key": "buyChannel"
}
"__typename": "LineItem"
}
],
"id": "ef6ab2b4-538d-4490-a491-1db561101590",
"__typename": "Order"
},
{
"lineItems": [
{
"id": "93041518-7766-4625-a596-567d41606db9",
"distributionChannel": {
"id": "9c5b1a2a-52dd-4cef-b914-94d2332c5c4f",
"key": "sellChannel"
}
"__typename": "LineItem"
}
],
"id": "06814bde-89a8-4009-a8af-87e031dd10ef",
"__typename": "Order"
},
{
"lineItems": [
{
"id": "81b9aa6c-c631-429b-8227-f21100968720",
"distributionChannel": {
"id": "002f67cb-7f2e-48d2-a164-01b2857fcc59",
"key": "sellChannel"
},
"__typename": "LineItem"
},
{
"id": "003797a0-3142-4162-849b-3f0661e3aff5",
"distributionChannel": {
"id": "002f67cb-7f2e-48d2-a164-01b2857fcc59",
"key": "sellChannel"
}
"__typename": "LineItem"
}
],
"id": "631b9945-c30e-4c92-9a01-7635988c7c78",
"__typename": "Order"
}
]
I need to search for objects which have distributionChannel.key === 'sellChannel'
, which is inside lineItems
.
Expected output:
[
{
"lineItems": [
{
"id": "93041518-7766-4625-a596-567d41606db9",
"distributionChannel": {
"id": "9c5b1a2a-52dd-4cef-b914-94d2332c5c4f",
"key": "sellChannel"
}
"__typename": "LineItem"
}
],
"id": "06814bde-89a8-4009-a8af-87e031dd10ef",
"__typename": "Order"
},
{
"lineItems": [
{
"id": "81b9aa6c-c631-429b-8227-f21100968720",
"distributionChannel": {
"id": "002f67cb-7f2e-48d2-a164-01b2857fcc59",
"key": "sellChannel"
},
"__typename": "LineItem"
},
{
"id": "003797a0-3142-4162-849b-3f0661e3aff5",
"distributionChannel": {
"id": "002f67cb-7f2e-48d2-a164-01b2857fcc59",
"key": "sellChannel"
}
"__typename": "LineItem"
}
],
"id": "631b9945-c30e-4c92-9a01-7635988c7c78",
"__typename": "Order"
}
]
Any ideas how can I handle it?
CodePudding user response:
Filter the original array based on which elements contain list items where some have a distribution key equal to sellChannel:
const results = arr.filter(el =>
el.lineItems.some(li =>
li.distributionChannel.key === 'sellChannel'))
Note that if any line items contain both sellChannel and buyChannel entries, they will also be returned.