Related
I am trying to filter a multidimensional array with the inner array containing an object. Every post I have found on here looks like the example below, and all the solutions were pretty much the same and were not successful for me.
let arr = [ { name: 'brent', age: 123 } ];
This is closest I can get, I can console log the filter and see it filtering, but I cannot find out why my array is returning undefined.
let filteredData = [];
let responseData.results = [...]; //The contents of this array are below in the next block
filteredData = responseData.results.forEach((group) =>
{
group.filter(({ customerName }) => customerName.includes(searchTerm));
});
console.log(filteredData); //returns as undefined?
let responseData.results = [
[
{
"id": "e62d6610-04aa-4e92-806f-0449ab3becad",
"customerName": "Immunics",
"enduserName": "Everest",
"productId": 4,
"productName": "fugiat",
"createdBy": "Keith",
"created": "2013-10-31",
"expires": "2011-03-03"
},
{
"id": "3be2967d-cd92-488b-97e3-a8001da6d1c5",
"customerName": "Techtrix",
"enduserName": "Lunchpad",
"productId": 2,
"productName": "sit",
"createdBy": "Odessa",
"created": "2010-02-25",
"expires": "2011-05-22"
},
{
"id": "a67861ae-4e1b-4637-af45-096d6ed7a50f",
"customerName": "Kaggle",
"enduserName": "Strezzo",
"productId": 4,
"productName": "consequat",
"createdBy": "Matilda",
"created": "2010-09-05",
"expires": "2011-08-01"
},
{
"id": "182f84d5-fc27-414c-b011-0e26a9b8e688",
"customerName": "Idealis",
"enduserName": "Blurrybus",
"productId": 0,
"productName": "veniam",
"createdBy": "Merle",
"created": "2012-02-02",
"expires": "2014-05-22"
},
{
"id": "cc05e705-3b5f-4fe6-8c6e-1873fd3834ac",
"customerName": "Furnigeer",
"enduserName": "Harmoney",
"productId": 5,
"productName": "anim",
"createdBy": "Humphrey",
"created": "2010-08-15",
"expires": "2012-06-06"
}
],
[
{
"id": "f2d0ff8e-31ad-4415-8089-cce9df68d119",
"customerName": "Neocent",
"enduserName": "Inear",
"productId": 3,
"productName": "duis",
"createdBy": "Christian",
"created": "2010-01-23",
"expires": "2013-05-18"
},
{
"id": "485095fa-ac86-475c-9a7c-ad449334060d",
"customerName": "Digiprint",
"enduserName": "Bristo",
"productId": 0,
"productName": "occaecat",
"createdBy": "Moran",
"created": "2010-09-30",
"expires": "2014-06-14"
},
{
"id": "d3cacece-1f96-4055-8672-4e506b73e437",
"customerName": "Nexgene",
"enduserName": "Viasia",
"productId": 7,
"productName": "exercitation",
"createdBy": "John",
"created": "2012-07-23",
"expires": "2014-03-31"
},
{
"id": "7fe019e3-7175-48a0-9e2d-1681ce1bfb64",
"customerName": "Quilm",
"enduserName": "Hawkster",
"productId": 3,
"productName": "do",
"createdBy": "Stevens",
"created": "2014-04-28",
"expires": "2013-07-27"
},
{
"id": "7c83a2ea-aa43-4413-af86-02fcd20740e3",
"customerName": "Zillacon",
"enduserName": "Zanity",
"productId": 5,
"productName": "dolor",
"createdBy": "Cathryn",
"created": "2010-07-05",
"expires": "2011-11-26"
}
],
[
{
"id": "2fc29e02-ae0c-413f-ba5a-270a8ba73e5a",
"customerName": "Zepitope",
"enduserName": "Cujo",
"productId": 4,
"productName": "quis",
"createdBy": "Aurora",
"created": "2013-03-22",
"expires": "2014-09-27"
},
{
"id": "07020c5e-7512-456b-af77-3f95d3b8724b",
"customerName": "Melbacor",
"enduserName": "Elemantra",
"productId": 0,
"productName": "amet",
"createdBy": "Pitts",
"created": "2010-09-06",
"expires": "2014-08-14"
},
{
"id": "be9ecd9d-7060-43a2-83b8-b05c52954b9c",
"customerName": "Combot",
"enduserName": "Circum",
"productId": 7,
"productName": "ex",
"createdBy": "Mindy",
"created": "2013-07-05",
"expires": "2014-07-26"
},
{
"id": "991a986b-bd3b-426a-9fc8-113a312c4a19",
"customerName": "Canopoly",
"enduserName": "Accusage",
"productId": 3,
"productName": "proident",
"createdBy": "Cohen",
"created": "2014-02-09",
"expires": "2011-03-17"
},
{
"id": "d843e391-c56d-4dc4-a1d1-dc1b936bc9bd",
"customerName": "Mobildata",
"enduserName": "Eargo",
"productId": 4,
"productName": "culpa",
"createdBy": "Kathie",
"created": "2013-04-03",
"expires": "2012-07-03"
}
],
[
{
"id": "940c6df9-0bbb-43d0-a463-23ba6754a0bb",
"customerName": "Signity",
"enduserName": "Bovis",
"productId": 8,
"productName": "occaecat",
"createdBy": "Monroe",
"created": "2013-09-03",
"expires": "2014-03-23"
},
{
"id": "7479851f-8bba-448b-9af4-75076d81c61f",
"customerName": "Zilladyne",
"enduserName": "Mazuda",
"productId": 8,
"productName": "voluptate",
"createdBy": "Bertie",
"created": "2012-05-03",
"expires": "2010-09-11"
},
{
"id": "dda601dc-6671-43ca-847f-53a90e61f123",
"customerName": "Farmex",
"enduserName": "Greeker",
"productId": 7,
"productName": "eiusmod",
"createdBy": "Jody",
"created": "2010-06-17",
"expires": "2010-09-19"
},
{
"id": "dee1e763-bc49-4b14-87c9-41c7dee01763",
"customerName": "Fibrodyne",
"enduserName": "Besto",
"productId": 7,
"productName": "ex",
"createdBy": "Arlene",
"created": "2012-01-29",
"expires": "2013-10-14"
},
{
"id": "89d69c32-c801-469f-b40f-3d8c85184b08",
"customerName": "Sustenza",
"enduserName": "Omatom",
"productId": 9,
"productName": "consectetur",
"createdBy": "Pruitt",
"created": "2011-03-24",
"expires": "2014-09-13"
}
],
[
{
"id": "2a1d82fc-d7df-4fde-bd4c-97fabccf217e",
"customerName": "Essensia",
"enduserName": "Comverges",
"productId": 8,
"productName": "aliquip",
"createdBy": "White",
"created": "2010-06-23",
"expires": "2014-04-02"
},
{
"id": "f16e04f8-8431-43ac-8315-9822435fe9b0",
"customerName": "Accruex",
"enduserName": "Gluid",
"productId": 6,
"productName": "veniam",
"createdBy": "Kim",
"created": "2010-07-14",
"expires": "2010-04-09"
},
{
"id": "47728404-a86a-4f91-a4fb-d54c6da88a74",
"customerName": "Miracula",
"enduserName": "Gonkle",
"productId": 2,
"productName": "proident",
"createdBy": "Moon",
"created": "2013-07-08",
"expires": "2010-09-10"
},
{
"id": "96810031-64e0-4565-ae0f-308db3fbf7eb",
"customerName": "Viocular",
"enduserName": "Toyletry",
"productId": 3,
"productName": "sit",
"createdBy": "Callahan",
"created": "2014-10-28",
"expires": "2011-01-11"
},
{
"id": "fd223cf3-7f1b-4afb-bccf-cf1907a33334",
"customerName": "Genekom",
"enduserName": "Chorizon",
"productId": 3,
"productName": "ipsum",
"createdBy": "Calhoun",
"created": "2013-09-12",
"expires": "2011-02-27"
}
]
]
You have two common ways of going about this.
Either you can do a map:
const filteredData = responseData.results.map((group) => {
return group.filter(({ customerName }) => customerName.includes(searchTerm));
});
Or even shorter with the implicit inline return:
const filteredData = responseData.results.map((group) =>
group.filter(({ customerName }) => customerName.includes(searchTerm))
);
Or a reduce to get rid of the non-filtered objects that provide a hit from responseData.
const filteredData = responseData.results.reduce((result, group) => {
const match = group.filter(({ customerName }) =>
customerName.includes(searchTerm)
);
if (match) result.push(match);
return result;
}, []);
More information:
MDN - reduce()
MDN - map()
It's a variable naming mistake. You haven't changed filteredData. Rename filteredLicenses to filteredData and it should work.
You may use reduce method to filter each group (sub array) and push those filtered groups to the resulting array if the filtered group has at least one item. Using map method will push empty groups to the resulting array and that's why reduce should be used to prevent that.
Here's a live demo:
const results = [
[{
"id": "e62d6610-04aa-4e92-806f-0449ab3becad",
"customerName": "Immunics",
"enduserName": "Everest",
"productId": 4,
"productName": "fugiat",
"createdBy": "Keith",
"created": "2013-10-31",
"expires": "2011-03-03"
},
{
"id": "3be2967d-cd92-488b-97e3-a8001da6d1c5",
"customerName": "Techtrix",
"enduserName": "Lunchpad",
"productId": 2,
"productName": "sit",
"createdBy": "Odessa",
"created": "2010-02-25",
"expires": "2011-05-22"
},
{
"id": "a67861ae-4e1b-4637-af45-096d6ed7a50f",
"customerName": "Kaggle",
"enduserName": "Strezzo",
"productId": 4,
"productName": "consequat",
"createdBy": "Matilda",
"created": "2010-09-05",
"expires": "2011-08-01"
},
{
"id": "182f84d5-fc27-414c-b011-0e26a9b8e688",
"customerName": "Idealis",
"enduserName": "Blurrybus",
"productId": 0,
"productName": "veniam",
"createdBy": "Merle",
"created": "2012-02-02",
"expires": "2014-05-22"
},
{
"id": "cc05e705-3b5f-4fe6-8c6e-1873fd3834ac",
"customerName": "Furnigeer",
"enduserName": "Harmoney",
"productId": 5,
"productName": "anim",
"createdBy": "Humphrey",
"created": "2010-08-15",
"expires": "2012-06-06"
}
],
[{
"id": "f2d0ff8e-31ad-4415-8089-cce9df68d119",
"customerName": "Neocent",
"enduserName": "Inear",
"productId": 3,
"productName": "duis",
"createdBy": "Christian",
"created": "2010-01-23",
"expires": "2013-05-18"
},
{
"id": "485095fa-ac86-475c-9a7c-ad449334060d",
"customerName": "Digiprint",
"enduserName": "Bristo",
"productId": 0,
"productName": "occaecat",
"createdBy": "Moran",
"created": "2010-09-30",
"expires": "2014-06-14"
},
{
"id": "d3cacece-1f96-4055-8672-4e506b73e437",
"customerName": "Nexgene",
"enduserName": "Viasia",
"productId": 7,
"productName": "exercitation",
"createdBy": "John",
"created": "2012-07-23",
"expires": "2014-03-31"
},
{
"id": "7fe019e3-7175-48a0-9e2d-1681ce1bfb64",
"customerName": "Quilm",
"enduserName": "Hawkster",
"productId": 3,
"productName": "do",
"createdBy": "Stevens",
"created": "2014-04-28",
"expires": "2013-07-27"
},
{
"id": "7c83a2ea-aa43-4413-af86-02fcd20740e3",
"customerName": "Zillacon",
"enduserName": "Zanity",
"productId": 5,
"productName": "dolor",
"createdBy": "Cathryn",
"created": "2010-07-05",
"expires": "2011-11-26"
}
],
[{
"id": "2fc29e02-ae0c-413f-ba5a-270a8ba73e5a",
"customerName": "Zepitope",
"enduserName": "Cujo",
"productId": 4,
"productName": "quis",
"createdBy": "Aurora",
"created": "2013-03-22",
"expires": "2014-09-27"
},
{
"id": "07020c5e-7512-456b-af77-3f95d3b8724b",
"customerName": "Melbacor",
"enduserName": "Elemantra",
"productId": 0,
"productName": "amet",
"createdBy": "Pitts",
"created": "2010-09-06",
"expires": "2014-08-14"
},
{
"id": "be9ecd9d-7060-43a2-83b8-b05c52954b9c",
"customerName": "Combot",
"enduserName": "Circum",
"productId": 7,
"productName": "ex",
"createdBy": "Mindy",
"created": "2013-07-05",
"expires": "2014-07-26"
},
{
"id": "991a986b-bd3b-426a-9fc8-113a312c4a19",
"customerName": "Canopoly",
"enduserName": "Accusage",
"productId": 3,
"productName": "proident",
"createdBy": "Cohen",
"created": "2014-02-09",
"expires": "2011-03-17"
},
{
"id": "d843e391-c56d-4dc4-a1d1-dc1b936bc9bd",
"customerName": "Mobildata",
"enduserName": "Eargo",
"productId": 4,
"productName": "culpa",
"createdBy": "Kathie",
"created": "2013-04-03",
"expires": "2012-07-03"
}
],
[{
"id": "940c6df9-0bbb-43d0-a463-23ba6754a0bb",
"customerName": "Signity",
"enduserName": "Bovis",
"productId": 8,
"productName": "occaecat",
"createdBy": "Monroe",
"created": "2013-09-03",
"expires": "2014-03-23"
},
{
"id": "7479851f-8bba-448b-9af4-75076d81c61f",
"customerName": "Zilladyne",
"enduserName": "Mazuda",
"productId": 8,
"productName": "voluptate",
"createdBy": "Bertie",
"created": "2012-05-03",
"expires": "2010-09-11"
},
{
"id": "dda601dc-6671-43ca-847f-53a90e61f123",
"customerName": "Farmex",
"enduserName": "Greeker",
"productId": 7,
"productName": "eiusmod",
"createdBy": "Jody",
"created": "2010-06-17",
"expires": "2010-09-19"
},
{
"id": "dee1e763-bc49-4b14-87c9-41c7dee01763",
"customerName": "Fibrodyne",
"enduserName": "Besto",
"productId": 7,
"productName": "ex",
"createdBy": "Arlene",
"created": "2012-01-29",
"expires": "2013-10-14"
},
{
"id": "89d69c32-c801-469f-b40f-3d8c85184b08",
"customerName": "Sustenza",
"enduserName": "Omatom",
"productId": 9,
"productName": "consectetur",
"createdBy": "Pruitt",
"created": "2011-03-24",
"expires": "2014-09-13"
}
],
[{
"id": "2a1d82fc-d7df-4fde-bd4c-97fabccf217e",
"customerName": "Essensia",
"enduserName": "Comverges",
"productId": 8,
"productName": "aliquip",
"createdBy": "White",
"created": "2010-06-23",
"expires": "2014-04-02"
},
{
"id": "f16e04f8-8431-43ac-8315-9822435fe9b0",
"customerName": "Accruex",
"enduserName": "Gluid",
"productId": 6,
"productName": "veniam",
"createdBy": "Kim",
"created": "2010-07-14",
"expires": "2010-04-09"
},
{
"id": "47728404-a86a-4f91-a4fb-d54c6da88a74",
"customerName": "Miracula",
"enduserName": "Gonkle",
"productId": 2,
"productName": "proident",
"createdBy": "Moon",
"created": "2013-07-08",
"expires": "2010-09-10"
},
{
"id": "96810031-64e0-4565-ae0f-308db3fbf7eb",
"customerName": "Viocular",
"enduserName": "Toyletry",
"productId": 3,
"productName": "sit",
"createdBy": "Callahan",
"created": "2014-10-28",
"expires": "2011-01-11"
},
{
"id": "fd223cf3-7f1b-4afb-bccf-cf1907a33334",
"customerName": "Genekom",
"enduserName": "Chorizon",
"productId": 3,
"productName": "ipsum",
"createdBy": "Calhoun",
"created": "2013-09-12",
"expires": "2011-02-27"
}
]
],
/**
* a function that filters the "results" array based on a "searchTerm"
*/
filterResults = searchTerm => results.reduce((r, group) => {
const f = group.filter(({customerName}) => customerName.includes(searchTerm));
/** only push NON empty groups (sub arrays) to the final array */
f.length && r.push(f);
return r;
}, []);
/** test "fileterResults" function */
console.log(filterResults("Farmex"));
.as-console-wrapper {
max-height: 100%!important;
}
I have an array of elements whom I am try to do total of few columns.
I have read about reduce method with destructuring the elements from it.
But problem is that I can't able to pass multiple params in it.
Plus it does not recognise the passed element in it.
Here is my code:
const prob = h.lead_plans.reduce((currentTotal, currentDau) => {
console.log(currentDau.probability);
return ({'probability'} = {probability: ((currentTotal || 0) + currentDau.probability)})
}, {probability: 0});
Expected code:
const prob = h.lead_plans.reduce((currentTotal, currentDau) => {
return ({probability,plan2} = {
probability: ((currentTotal || 0) + currentDau.probability),
plan2: ((currentTotal || 0) + currentDau.plan2),
})
}, {probability: 0, plan2: 0});
In return as a final result, I will be getting the sum of inner columns based on destructuring structure.
Adding Hash:
Here is my hash:
{
"success": true,
"leads": [
{
"id": 9,
"branch": "Accounts",
"classification": "Warm",
"theme": "Lean",
"branch_id": 3,
"classification_id": 1,
"project_id": 30,
"theme_id": 3,
"projectname": "project test",
"comment": "commenters",
"customername": "alex",
"lead1id": 2,
"lead1percent": "2.0",
"lead2id": 2,
"lead2percent": "2.0",
"lead3id": 2,
"lead3percent": "2.0",
"lead_plans": [
{
"id": 5,
"lead_id": 9,
"addcosts": "2.0",
"fee": "2.0",
"plan2": "2.0",
"plan3": "2.0",
"probability": "2.0",
"year": "2020-02-12"
}
],
"offers": [
{
"id": 5,
"lead_id": 9,
"addcosts": "2.0",
"addcostsinfo": "some info",
"days": "2020-02-12",
"decision": "good",
"decisiondate": "2020-02-12",
"fee": "2.0",
"mail": "mail goes here",
"offerdate": "2020-02-12",
"paper": "xyz"
}
]
},
{
"id": 10,
"branch": "Accounts",
"classification": "Warm",
"theme": "Lean",
"branch_id": 3,
"classification_id": 1,
"project_id": 28,
"theme_id": 3,
"projectname": "project test",
"comment": "commenters",
"customername": "alex",
"lead1id": 2,
"lead1percent": "2.0",
"lead2id": 2,
"lead2percent": "2.0",
"lead3id": 2,
"lead3percent": "2.0",
"lead_plans": [
{
"id": 6,
"lead_id": 10,
"addcosts": "2.0",
"fee": "2.0",
"plan2": "2.0",
"plan3": "2.0",
"probability": "2.0",
"year": "2020-02-12"
}
],
"offers": [
{
"id": 6,
"lead_id": 10,
"addcosts": "2.0",
"addcostsinfo": "some info",
"days": "2020-02-12",
"decision": "good",
"decisiondate": "2020-02-12",
"fee": "2.0",
"mail": "mail goes here",
"offerdate": "2020-02-12",
"paper": "xyz"
}
]
},
{
"id": 11,
"branch": "Accounts",
"classification": "Warm",
"theme": "Lean",
"branch_id": 3,
"classification_id": 1,
"project_id": 30,
"theme_id": 3,
"projectname": "project test",
"comment": "commenters",
"customername": "alex",
"lead1id": 2,
"lead1percent": "2.0",
"lead2id": 2,
"lead2percent": "2.0",
"lead3id": 2,
"lead3percent": "2.0",
"lead_plans": [
{
"id": 7,
"lead_id": 11,
"addcosts": "2.0",
"fee": "2.0",
"plan2": "2.0",
"plan3": "2.0",
"probability": "2.0",
"year": "2020-02-12"
},
{
"id": 8,
"lead_id": 11,
"addcosts": "6.0",
"fee": "5.0",
"plan2": "4.0",
"plan3": "3.0",
"probability": "6.0",
"year": "2020-02-12"
},
{
"id": 9,
"lead_id": 11,
"addcosts": "5.0",
"fee": "2.0",
"plan2": "5.0",
"plan3": "1.0",
"probability": "3.0",
"year": "2020-02-12"
}
],
"offers": [
{
"id": 7,
"lead_id": 11,
"addcosts": "2.0",
"addcostsinfo": "some info",
"days": "2020-02-12",
"decision": "good",
"decisiondate": "2020-02-12",
"fee": "2.0",
"mail": "mail goes here",
"offerdate": "2020-02-12",
"paper": "xyz"
},
{
"id": 8,
"lead_id": 11,
"addcosts": "7.0",
"addcostsinfo": "some info",
"days": "2020-02-12",
"decision": "good",
"decisiondate": "2020-02-12",
"fee": "9.0",
"mail": "mail goes here",
"offerdate": "2020-02-12",
"paper": "xyz"
},
{
"id": 9,
"lead_id": 11,
"addcosts": "8.0",
"addcostsinfo": "some info",
"days": "2020-02-12",
"decision": "good",
"decisiondate": "2020-02-12",
"fee": "7.0",
"mail": "mail goes here",
"offerdate": "2020-02-12",
"paper": "xyzas"
}
]
},
{
"id": 11,
"branch": "Accounts",
"classification": "Warm",
"theme": "Lean",
"branch_id": 3,
"classification_id": 1,
"project_id": 30,
"theme_id": 3,
"projectname": "project test",
"comment": "commenters",
"customername": "alex",
"lead1id": 2,
"lead1percent": "2.0",
"lead2id": 2,
"lead2percent": "2.0",
"lead3id": 2,
"lead3percent": "2.0",
"lead_plans": [
{
"id": 7,
"lead_id": 11,
"addcosts": "2.0",
"fee": "2.0",
"plan2": "2.0",
"plan3": "2.0",
"probability": "2.0",
"year": "2020-02-12"
},
{
"id": 8,
"lead_id": 11,
"addcosts": "6.0",
"fee": "5.0",
"plan2": "4.0",
"plan3": "3.0",
"probability": "6.0",
"year": "2020-02-12"
},
{
"id": 9,
"lead_id": 11,
"addcosts": "5.0",
"fee": "2.0",
"plan2": "5.0",
"plan3": "1.0",
"probability": "3.0",
"year": "2020-02-12"
}
],
"offers": [
{
"id": 7,
"lead_id": 11,
"addcosts": "2.0",
"addcostsinfo": "some info",
"days": "2020-02-12",
"decision": "good",
"decisiondate": "2020-02-12",
"fee": "2.0",
"mail": "mail goes here",
"offerdate": "2020-02-12",
"paper": "xyz"
},
{
"id": 8,
"lead_id": 11,
"addcosts": "7.0",
"addcostsinfo": "some info",
"days": "2020-02-12",
"decision": "good",
"decisiondate": "2020-02-12",
"fee": "9.0",
"mail": "mail goes here",
"offerdate": "2020-02-12",
"paper": "xyz"
},
{
"id": 9,
"lead_id": 11,
"addcosts": "8.0",
"addcostsinfo": "some info",
"days": "2020-02-12",
"decision": "good",
"decisiondate": "2020-02-12",
"fee": "7.0",
"mail": "mail goes here",
"offerdate": "2020-02-12",
"paper": "xyzas"
}
]
},
{
"id": 11,
"branch": "Accounts",
"classification": "Warm",
"theme": "Lean",
"branch_id": 3,
"classification_id": 1,
"project_id": 30,
"theme_id": 3,
"projectname": "project test",
"comment": "commenters",
"customername": "alex",
"lead1id": 2,
"lead1percent": "2.0",
"lead2id": 2,
"lead2percent": "2.0",
"lead3id": 2,
"lead3percent": "2.0",
"lead_plans": [
{
"id": 7,
"lead_id": 11,
"addcosts": "2.0",
"fee": "2.0",
"plan2": "2.0",
"plan3": "2.0",
"probability": "2.0",
"year": "2020-02-12"
},
{
"id": 8,
"lead_id": 11,
"addcosts": "6.0",
"fee": "5.0",
"plan2": "4.0",
"plan3": "3.0",
"probability": "6.0",
"year": "2020-02-12"
},
{
"id": 9,
"lead_id": 11,
"addcosts": "5.0",
"fee": "2.0",
"plan2": "5.0",
"plan3": "1.0",
"probability": "3.0",
"year": "2020-02-12"
}
],
"offers": [
{
"id": 7,
"lead_id": 11,
"addcosts": "2.0",
"addcostsinfo": "some info",
"days": "2020-02-12",
"decision": "good",
"decisiondate": "2020-02-12",
"fee": "2.0",
"mail": "mail goes here",
"offerdate": "2020-02-12",
"paper": "xyz"
},
{
"id": 8,
"lead_id": 11,
"addcosts": "7.0",
"addcostsinfo": "some info",
"days": "2020-02-12",
"decision": "good",
"decisiondate": "2020-02-12",
"fee": "9.0",
"mail": "mail goes here",
"offerdate": "2020-02-12",
"paper": "xyz"
},
{
"id": 9,
"lead_id": 11,
"addcosts": "8.0",
"addcostsinfo": "some info",
"days": "2020-02-12",
"decision": "good",
"decisiondate": "2020-02-12",
"fee": "7.0",
"mail": "mail goes here",
"offerdate": "2020-02-12",
"paper": "xyzas"
}
]
}
],
"message": "Projects fetched successfully"
}
Currently, its working for me but I am forced to write 3 codes for one job.
Working code:
const probability = h.lead_plans.reduce((currentTotal, currentDau) => parseFloat((currentTotal || 0)) + parseFloat(currentDau.probability), 0)
const plan2 = h.lead_plans.reduce((currentTotal, currentDau) => parseFloat((currentTotal || 0)) + parseFloat(currentDau.plan2), 0)
const plan3 = h.lead_plans.reduce((currentTotal, currentDau) => parseFloat((currentTotal || 0)) + parseFloat(currentDau.plan3), 0)
Here's how the code would work. The currentTotal value on the first run through is the second argument to the reduce function Array#reduce(function,initialValue) which is {probability: 0, plan2: 0} rather than a number.
So, you don't need to do any object destructuring, you just need to use the accumulator to sum the individual keys of the object you want, and then return those new values. Then your end result will be of the same type that you used for the initialValue.
This casts the probability and plan2 values to numbers so they'll be able to properly be summed.
const h = {
lead_plans: [{
probability: '2.2',
plan2: '5.2'
}, {
probability: '7.8',
plan2: '3.1'
}, {
probability: '1.8',
plan2: '2.3'
}]
}
const result = h.lead_plans.reduce(
(accumulator, currentDau) => {
return {
probability: accumulator.probability + parseFloat((currentDau.probability || 0)),
plan2: accumulator.plan2 + parseFloat((currentDau.plan2 || 0)),
};
}, {
probability: 0,
plan2: 0
}
);
console.log(result);
Here's an example of how to make a more re-usable reducer for summing all entries in an object:
Note, this is casting all keys to numbers, so they'll be NaN if there is a value that isn't a number.
const h = {
lead_plans: [{
probability: '2.5',
plan2: 5
}, {
probability: 7,
plan2: 3
}, {
probability: 1,
plan2: 2
}]
}
const reducerSumAll = (accumulator, object) => {
// Ensure there are no accidental mutations
const current = { ...accumulator };
for (const key of Object.keys(object)) {
// Make sure we are only accumulating the number types.
current[key] = parseFloat(current[key]||0) + parseFloat(object[key]||0);
}
return current;
};
const result = h.lead_plans.reduce(reducerSumAll)
console.log(result)
I have an array as following
[{
"id": 68,
"proffesional_photo": "",
"top_image": "https://sampleimage.jpg",
"ratings": "1",
"price": 690,
"description": null,
"type": true,
"promo": 0,
"status": true,
"item": {
"Item_name": "Dark Chocolate Latte"
},
"restaurant_dish_menus": [
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 4,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
},
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 3,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
}
]
},
{
"id": 69,
"proffesional_photo": "",
"top_image": "https://sampleimage2.jpg",
"ratings": "1",
"price": 700,
"description": null,
"type": true,
"promo": 0,
"status": true,
"item": {
"Item_name": "Latte"
},
"restaurant_dish_menus": [
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 3,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
}
]
}
],
And when the user select a certain menu it needs to be filtered through it,
Each dish objects may have more than one menu_id,
i attempted using array.filter but i am having trouble figuring out how to filter from the Dish array through the sub array within.
the code i attempted (filterBy = 4)
let result = data.filter(function(row) {
row.restaurant_dish_menus.filter(function(i) {
return i.menu_id == filterBy;
});
});
console.log(result) gives me an empty array.
if filterBy is = 4 the expected output is
{
"id": 68,
"proffesional_photo": "",
"top_image": "https://sampleimage.jpg",
"ratings": "1",
"price": 690,
"description": null,
"type": true,
"promo": 0,
"status": true,
"item": {
"Item_name": "Dark Chocolate Latte"
},
"restaurant_dish_menus": [
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 4,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
},
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 3,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
}
]
}
And if it filterBy is 3 then both objects should be the output
how about this
var data = [{
"id": 68,
"proffesional_photo": "",
"top_image": "https://sampleimage.jpg",
"ratings": "1",
"price": 690,
"description": null,
"type": true,
"promo": 0,
"status": true,
"item": {
"Item_name": "Dark Chocolate Latte"
},
"restaurant_dish_menus": [
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 4,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
},
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 3,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
}
]
}];
var result = data.filter(function(m) {
return m.restaurant_dish_menus.some(function(d) {
return d.menu_id === 4;
});
})
.filter expects the function passed to return a boolean. In your case, the function returns nothing (or undefined) which is always falsy.
One option is to use .find in the nested filter, and return a boolean depending on whether the result is undefined.
Here's a snippet.
let data = [{
"id": 68,
"proffesional_photo": "",
"top_image": "https://sampleimage.jpg",
"ratings": "1",
"price": 690,
"description": null,
"type": true,
"promo": 0,
"status": true,
"item": {
"Item_name": "Dark Chocolate Latte"
},
"restaurant_dish_menus": [{
"id": 1,
"res_dish_id": 1318,
"menu_id": 4,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
},
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 3,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
}
]
}, {
"id": 69,
"proffesional_photo": "",
"top_image": "https://sampleimage.jpg",
"ratings": "1",
"price": 690,
"description": null,
"type": true,
"promo": 0,
"status": true,
"item": {
"Item_name": "Dark Chocolate Latte"
},
"restaurant_dish_menus": [{
"id": 1,
"res_dish_id": 1318,
"menu_id": 6,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
},
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 5,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
}
]
}, ]
let filterBy = 4;
let result = data.filter(function(row) {
return row.restaurant_dish_menus.find(function(i) {
return i.menu_id == filterBy;
}) !== undefined;
});
console.log(result);
You can use "filter" as below
var data = [{
"id": 68,
"proffesional_photo": "",
"top_image": "https://sampleimage.jpg",
"ratings": "1",
"price": 690,
"description": null,
"type": true,
"promo": 0,
"status": true,
"item": {
"Item_name": "Dark Chocolate Latte"
},
"restaurant_dish_menus": [
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 4,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
},
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 3,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
}
]
},
{
"id": 69,
"proffesional_photo": "",
"top_image": "https://sampleimage2.jpg",
"ratings": "1",
"price": 700,
"description": null,
"type": true,
"promo": 0,
"status": true,
"item": {
"Item_name": "Latte"
},
"restaurant_dish_menus": [
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 3,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
}
]
}
]
function filterBy(f) {
return data.filter(d => d.restaurant_dish_menus.some(({ menu_id }) => menu_id == f))
}
console.log(filterBy(4))
console.log(filterBy(3))
You can also use grep function
var menus= {
"id": 68,
"proffesional_photo": "",
"top_image": "https://sampleimage.jpg",
"ratings": "1",
"price": 690,
"description": null,
"type": true,
"promo": 0,
"status": true,
"item": {
"Item_name": "Dark Chocolate Latte"
},
"restaurant_dish_menus": [
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 4,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
},
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 3,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
}
]
};
var found_names = $.grep(menus.restaurant_dish_menus, function(v) {
return v.menu_id ===4;
});
console.log(found_names);
http://jsfiddle.net/ejPV4/
Your question a bit unclear of final goal, but if you want to filter top level objects, i.e. if top level object has to be present if and only if it has dish with menu_id === filterBy, then:
let result = data.filter(row => {
return row.restaurant_dish_menus.some(({menu_id}) => menu_id === filterBy);
});
Above will only filter your rows if restaurant_dish_menus has items with menu_id === filterBy. But restaurant_dish_menus, of such objects remain unfiltered.
Result:
[{
"id": 68,
// skipped
"item": {
"Item_name": "Dark Chocolate Latte"
},
"restaurant_dish_menus": [
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 4,
// skipped
},
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 3,
// skipped
}
]
}]
But if you want to filter top level and filter restaurant_dish_menus also, i.e. modify top level object, then:
let result = data.filter(row => {
return row.restaurant_dish_menus.some(({menu_id}) => menu_id === filterBy);
}).map(row => {
return {...row, restaurant_dish_menus: row.restaurant_dish_menus.filter(i => i.menu_id === filterBy)};
});
This will first filter the row objects which has menu_id === filterBy, and then also filter restaurant_dish_menus, to include only once menu_id === filterBy, effectively modifying the row object, i.e. map.
Result:
[{
"id": 68,
// skipped
"item": {
"Item_name": "Dark Chocolate Latte"
},
"restaurant_dish_menus": [
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 4,
// skipped
}
]
}]
I am trying to create a report like given below with Node.js. The data is consumed from Microstrategy API.
Below is the JSON response I am getting from Microstrategy
{
"id": "12DC624040860B5401F516A2341D95C8",
"name": "Sales Report_AB.xlsx",
"instanceId": "A7900B0A4AD840FF327F04897A9DB4E3",
"result": {
"definition": {
"attributes": [
{
"name": "Branch Channel",
"id": "B449BEE543721EEB57501BBC1EDD1B3D",
"type": "Attribute",
"forms": [
{
"id": "45C11FA478E745FEA08D781CEA190FE5",
"name": "ID",
"dataType": "Char"
}
]
},
{
"name": "Branch City State",
"id": "2DF6E4204460A79BE3A86BA9F1FE9552",
"type": "Attribute",
"forms": [
{
"id": "45C11FA478E745FEA08D781CEA190FE5",
"name": "ID",
"dataType": "Char"
}
]
},
{
"name": "Client Full Name",
"id": "61460DC345A8EFDCCBCFB9AB0D3FEFAB",
"type": "Attribute",
"forms": [
{
"id": "45C11FA478E745FEA08D781CEA190FE5",
"name": "ID",
"dataType": "Char"
}
]
},
{
"name": "Firm",
"id": "145C2A3E45C369BEA82B9BA3C6CA68BF",
"type": "Attribute",
"forms": [
{
"id": "45C11FA478E745FEA08D781CEA190FE5",
"name": "ID",
"dataType": "Char"
}
]
},
{
"name": "Product Group",
"id": "5429196C44F9A365F0904DB2733C0209",
"type": "Attribute",
"forms": [
{
"id": "45C11FA478E745FEA08D781CEA190FE5",
"name": "ID",
"dataType": "Char"
}
]
},
{
"name": "Regional Manager (RM) MF",
"id": "DE85E29F45158ED9C5B35082B399A22E",
"type": "Attribute",
"forms": [
{
"id": "45C11FA478E745FEA08D781CEA190FE5",
"name": "ID",
"dataType": "Char"
}
]
}
],
"metrics": [
{
"name": "Branch Rank",
"id": "975BE0ED4174AA52C0AF97A96D64CE7B",
"type": "Metric",
"min": 4,
"max": 103,
"numberFormatting": {
"category": 7,
"decimalPlaces": 0,
"formatString": "#,##0;\"(\"#,##0\")\""
}
},
{
"name": "MF & SMA Current AUM",
"id": "33B375744FA4A91B86A87D9FE4EEE718",
"type": "Metric",
"min": 145865.48,
"max": 10530391.47,
"numberFormatting": {
"category": 7,
"decimalPlaces": 0,
"formatString": "#,##0;\"(\"#,##0\")\""
}
},
{
"name": "MF & SMA Today Sales",
"id": "82F9DD1D4F6AC5EBA77D918D0541B9AD",
"type": "Metric",
"min": 15.34,
"max": 1315.91,
"numberFormatting": {
"category": 7,
"decimalPlaces": 0,
"formatString": "#,##0;\"(\"#,##0\")\""
}
},
{
"name": "MF & SMA Pr. Month Sales",
"id": "3890BF0C4553300D5467A7A871C66F76",
"type": "Metric",
"min": 388.56,
"max": 60365.82,
"numberFormatting": {
"category": 7,
"decimalPlaces": 0,
"formatString": "#,##0;\"(\"#,##0\")\""
}
},
{
"name": "RET Today Sales",
"id": "99DC7CD344B5B5C6DD337989077BC478",
"type": "Metric",
"min": 15.34,
"max": 1315.91,
"numberFormatting": {
"category": 7,
"decimalPlaces": 0,
"formatString": "#,##0;\"(\"#,##0\")\""
}
},
{
"name": "RET Current AUM",
"id": "981FE7E34CE4D6C3543B2B8E0367ECAA",
"type": "Metric",
"min": 46170.04,
"max": 3172313.93,
"numberFormatting": {
"category": 7,
"decimalPlaces": 0,
"formatString": "#,##0;\"(\"#,##0\")\""
}
}
],
"thresholds": []
},
"data": {
"paging": {
"total": 5,
"current": 5,
"offset": 0,
"limit": 1000,
"prev": null,
"next": null
},
"root": {
"isPartial": false,
"children": [
{
"depth": 0,
"element": {
"attributeIndex": 0,
"formValues": {
"ID": "Broker Dealer"
},
"name": "Broker Dealer",
"id": "hBroker Dealer;B449BEE543721EEB57501BBC1EDD1B3D"
},
"isPartial": false,
"children": [
{
"depth": 1,
"element": {
"attributeIndex": 1,
"formValues": {
"ID": "BILLINGS"
},
"name": "BILLINGS",
"id": "hBILLINGS;2DF6E4204460A79BE3A86BA9F1FE9552"
},
"isPartial": false,
"children": [
{
"depth": 2,
"element": {
"attributeIndex": 2,
"formValues": {
"ID": "TODD H VRALSTED"
},
"name": "TODD H VRALSTED",
"id": "hTODD H VRALSTED;61460DC345A8EFDCCBCFB9AB0D3FEFAB"
},
"isPartial": false,
"children": [
{
"depth": 3,
"element": {
"attributeIndex": 3,
"formValues": {
"ID": "UBS FINANCIAL SERVICES INC."
},
"name": "UBS FINANCIAL SERVICES INC.",
"id": "hUBS FINANCIAL SERVICES INC.;145C2A3E45C369BEA82B9BA3C6CA68BF"
},
"isPartial": false,
"children": [
{
"depth": 4,
"element": {
"attributeIndex": 4,
"formValues": {
"ID": "GLOBAL BOND"
},
"name": "GLOBAL BOND",
"id": "hGLOBAL BOND;5429196C44F9A365F0904DB2733C0209"
},
"isPartial": false,
"children": [
{
"depth": 5,
"element": {
"attributeIndex": 5,
"formValues": {
"ID": "Doss Steve"
},
"name": "Doss Steve",
"id": "hDoss Steve;DE85E29F45158ED9C5B35082B399A22E"
},
"metrics": {
"Branch Rank": {
"rv": 4,
"fv": "4",
"mi": 0
},
"MF & SMA Current AUM": {
"rv": 567490.58,
"fv": "567,491",
"mi": 1
},
"MF & SMA Today Sales": {
"rv": 15.34,
"fv": "15",
"mi": 2
},
"MF & SMA Pr. Month Sales": {
"rv": 388.56,
"fv": "389",
"mi": 3
},
"RET Today Sales": {
"rv": 15.34,
"fv": "15",
"mi": 4
},
"RET Current AUM": {
"rv": 46170.04,
"fv": "46,170",
"mi": 5
}
}
}
]
},
{
"depth": 4,
"element": {
"attributeIndex": 4,
"formValues": {
"ID": "LARGE CAP GROWTH"
},
"name": "LARGE CAP GROWTH",
"id": "hLARGE CAP GROWTH;5429196C44F9A365F0904DB2733C0209"
},
"isPartial": false,
"children": [
{
"depth": 5,
"element": {
"attributeIndex": 5,
"formValues": {
"ID": "Doss Steve"
},
"name": "Doss Steve",
"id": "hDoss Steve;DE85E29F45158ED9C5B35082B399A22E"
},
"metrics": {
"Branch Rank": {
"rv": 4,
"fv": "4",
"mi": 0
},
"MF & SMA Current AUM": {
"rv": 10530391.47,
"fv": "10,530,391",
"mi": 1
},
"MF & SMA Today Sales": {
"rv": 763.74,
"fv": "764",
"mi": 2
},
"MF & SMA Pr. Month Sales": {
"rv": 60365.82,
"fv": "60,366",
"mi": 3
},
"RET Today Sales": {
"rv": 763.74,
"fv": "764",
"mi": 4
},
"RET Current AUM": {
"rv": 3172313.93,
"fv": "3,172,314",
"mi": 5
}
}
}
]
}
]
}
]
}
]
},
{
"depth": 1,
"element": {
"attributeIndex": 1,
"formValues": {
"ID": "BOULDER"
},
"name": "BOULDER",
"id": "hBOULDER;2DF6E4204460A79BE3A86BA9F1FE9552"
},
"isPartial": false,
"children": [
{
"depth": 2,
"element": {
"attributeIndex": 2,
"formValues": {
"ID": "RORY D LINDQUIST"
},
"name": "RORY D LINDQUIST",
"id": "hRORY D LINDQUIST;61460DC345A8EFDCCBCFB9AB0D3FEFAB"
},
"isPartial": false,
"children": [
{
"depth": 3,
"element": {
"attributeIndex": 3,
"formValues": {
"ID": "MORGAN STANLEY SMITH BARNEY LLC"
},
"name": "MORGAN STANLEY SMITH BARNEY LLC",
"id": "hMORGAN STANLEY SMITH BARNEY LLC;145C2A3E45C369BEA82B9BA3C6CA68BF"
},
"isPartial": false,
"children": [
{
"depth": 4,
"element": {
"attributeIndex": 4,
"formValues": {
"ID": "SMALL CAP GROWTH"
},
"name": "SMALL CAP GROWTH",
"id": "hSMALL CAP GROWTH;5429196C44F9A365F0904DB2733C0209"
},
"isPartial": false,
"children": [
{
"depth": 5,
"element": {
"attributeIndex": 5,
"formValues": {
"ID": "Doss Steve"
},
"name": "Doss Steve",
"id": "hDoss Steve;DE85E29F45158ED9C5B35082B399A22E"
},
"metrics": {
"Branch Rank": {
"rv": 103,
"fv": "103",
"mi": 0
},
"MF & SMA Current AUM": {
"rv": 339671.74,
"fv": "339,672",
"mi": 1
},
"MF & SMA Today Sales": {
"rv": 1315.91,
"fv": "1,316",
"mi": 2
},
"MF & SMA Pr. Month Sales": {
"rv": 3571.37,
"fv": "3,571",
"mi": 3
},
"RET Today Sales": {
"rv": 1315.91,
"fv": "1,316",
"mi": 4
},
"RET Current AUM": {
"rv": 339671.74,
"fv": "339,672",
"mi": 5
}
}
}
]
}
]
}
]
}
]
}
]
},
{
"depth": 0,
"element": {
"attributeIndex": 0,
"formValues": {
"ID": "Financial Advisor"
},
"name": "Financial Advisor",
"id": "hFinancial Advisor;B449BEE543721EEB57501BBC1EDD1B3D"
},
"isPartial": false,
"children": [
{
"depth": 1,
"element": {
"attributeIndex": 1,
"formValues": {
"ID": "DENVER"
},
"name": "DENVER",
"id": "hDENVER;2DF6E4204460A79BE3A86BA9F1FE9552"
},
"isPartial": false,
"children": [
{
"depth": 2,
"element": {
"attributeIndex": 2,
"formValues": {
"ID": "CHAD J LARSEN"
},
"name": "CHAD J LARSEN",
"id": "hCHAD J LARSEN;61460DC345A8EFDCCBCFB9AB0D3FEFAB"
},
"isPartial": false,
"children": [
{
"depth": 3,
"element": {
"attributeIndex": 3,
"formValues": {
"ID": "LPL FINANCIAL LLC"
},
"name": "LPL FINANCIAL LLC",
"id": "hLPL FINANCIAL LLC;145C2A3E45C369BEA82B9BA3C6CA68BF"
},
"isPartial": false,
"children": [
{
"depth": 4,
"element": {
"attributeIndex": 4,
"formValues": {
"ID": "SMALL CAP GROWTH"
},
"name": "SMALL CAP GROWTH",
"id": "hSMALL CAP GROWTH;5429196C44F9A365F0904DB2733C0209"
},
"isPartial": false,
"children": [
{
"depth": 5,
"element": {
"attributeIndex": 5,
"formValues": {
"ID": "Doss Steve"
},
"name": "Doss Steve",
"id": "hDoss Steve;DE85E29F45158ED9C5B35082B399A22E"
},
"metrics": {
"Branch Rank": {
"rv": 101,
"fv": "101",
"mi": 0
},
"MF & SMA Current AUM": {
"rv": 145865.48,
"fv": "145,865",
"mi": 1
},
"MF & SMA Today Sales": {
"rv": 322.84,
"fv": "323",
"mi": 2
},
"MF & SMA Pr. Month Sales": {
"rv": 1507.62,
"fv": "1,508",
"mi": 3
},
"RET Today Sales": {
"rv": 322.84,
"fv": "323",
"mi": 4
},
"RET Current AUM": {
"rv": 145865.48,
"fv": "145,865",
"mi": 5
}
}
}
]
}
]
}
]
},
{
"depth": 2,
"element": {
"attributeIndex": 2,
"formValues": {
"ID": "PATTERSON J MCKINLAY"
},
"name": "PATTERSON J MCKINLAY",
"id": "hPATTERSON J MCKINLAY;61460DC345A8EFDCCBCFB9AB0D3FEFAB"
},
"isPartial": false,
"children": [
{
"depth": 3,
"element": {
"attributeIndex": 3,
"formValues": {
"ID": "LPL FINANCIAL LLC"
},
"name": "LPL FINANCIAL LLC",
"id": "hLPL FINANCIAL LLC;145C2A3E45C369BEA82B9BA3C6CA68BF"
},
"isPartial": false,
"children": [
{
"depth": 4,
"element": {
"attributeIndex": 4,
"formValues": {
"ID": "HIGH INCOME"
},
"name": "HIGH INCOME",
"id": "hHIGH INCOME;5429196C44F9A365F0904DB2733C0209"
},
"isPartial": false,
"children": [
{
"depth": 5,
"element": {
"attributeIndex": 5,
"formValues": {
"ID": "Doss Steve"
},
"name": "Doss Steve",
"id": "hDoss Steve;DE85E29F45158ED9C5B35082B399A22E"
},
"metrics": {
"Branch Rank": {
"rv": 80,
"fv": "80",
"mi": 0
},
"MF & SMA Current AUM": {
"rv": 1545251.85,
"fv": "1,545,252",
"mi": 1
},
"MF & SMA Today Sales": {
"rv": 662.46,
"fv": "662",
"mi": 2
},
"MF & SMA Pr. Month Sales": {
"rv": 50635.32,
"fv": "50,635",
"mi": 3
},
"RET Today Sales": {
"rv": 662.46,
"fv": "662",
"mi": 4
},
"RET Current AUM": {
"rv": 1545251.85,
"fv": "1,545,252",
"mi": 5
}
}
}
]
}
]
}
]
}
]
}
]
}
]
}
}
}
}
The data is kind of a tree structure and I can vary from report to report, i.e. the number of sub-nodes and subcategories can change. So I need a dynamic code to build the same. I have tried something from my end and I am not able to build it in the way I want. Below is my code
var result = { "records": [] };
var res = test(records.result.data.root.children, result,[], 0);
console.log(res);
function test(records, result,items, index) {
_.forEach(records, function (value, key) {
items.push({"depth":value.depth,"name":value.element.name});
result.records[index] = items;
if(typeof value.children != "undefined") {
if(value.children.lenth > 1) {
index++;
}
test(value.children,result, items,index);
} else {
if(typeof value.metrics !== "undefined") {
_.forEach(value.metrics, function (v, k) {
items.push({mkey:k,mval:v.fv});
result.records[index] = items;
});
}
}
index++;
items = [];
});
return result;
}
The above code is using Lodash for array operations.
I'm not sure what exactly you want to collect to a flat array so I'm going to show you a general way how you can recursively traverse a node tree and collect all the nodes from it to an array.
Later you can do .filter, .map, etc. on the result to get any data you want.
function collectNodes(rootNode) {
const nodes = []
function visitNode(node) {
nodes.push(node)
if (node.children) {
node.children.forEach(visitNode)
}
}
visitNode(rootNode)
return nodes
}
const nodes = collectNodes(json.result.data.root)
I have the following code which I am using to filter one nested array with values from another nested array, but I am looking for the more fastest method.
const length = this.addedStateItems.length;
for (let i = 0; i < length; i++) {
if (this.addedStateItems[i].cities.length > 0) {
const tempCity: Array<BWCity> = [];
for (let k = 0; k < addedStates.length; k++) {
for (let l = 0; l < addedStates[k].Cities.length; l++) {
const city = this.addedStateItems[i].cities.find(item =>
item.name.toUpperCase().split(' ').join('_') === addedStates[k].Cities[l].CityName
);
if (city) {
tempCity.push(city);
}
}
}
this.addedStateItems[i].cities = tempCity;
}
}
JSON sample is as below:
this.addedStateItems = [
{
"isSelected": false,
"cities": [],
"name": "Alabama",
"code": "AL",
"sequence": 2,
"access": 2,
"id": 2
},
{
"isSelected": false,
"cities": [],
"name": "Alaska",
"code": "AK",
"sequence": 3,
"access": 3,
"id": 3
},
{
"isSelected": false,
"cities": [],
"name": "Arizona",
"code": "AZ",
"sequence": 4,
"access": 4,
"id": 4
},
{
"isSelected": false,
"cities": [],
"name": "Arkansas",
"code": "AR",
"sequence": 5,
"access": 5,
"id": 5
},
{
"isSelected": false,
"cities": [],
"name": "California",
"code": "CA",
"sequence": 6,
"access": 6,
"id": 6
},
{
"isSelected": false,
"cities": [],
"name": "Colorado",
"code": "CO",
"sequence": 7,
"access": 7,
"id": 7
},
{
"isSelected": false,
"cities": [],
"name": "Connecticut",
"code": "CT",
"sequence": 8,
"access": 8,
"id": 8
},
{
"isSelected": false,
"cities": [],
"name": "Delaware",
"code": "DE",
"sequence": 9,
"access": 9,
"id": 9
},
{
"isSelected": false,
"cities": [],
"name": "District of Columbia",
"code": "DC",
"sequence": 10,
"access": 10,
"id": 10
},
{
"isSelected": false,
"cities": [],
"name": "Florida",
"code": "FL",
"sequence": 11,
"access": 11,
"id": 11
},
{
"isSelected": false,
"cities": [],
"name": "Georgia",
"code": "GA",
"sequence": 12,
"access": 12,
"id": 12
},
{
"isSelected": false,
"cities": [],
"name": "Hawaii",
"code": "HI",
"sequence": 13,
"access": 13,
"id": 13
},
{
"isSelected": false,
"cities": [],
"name": "Idaho",
"code": "ID",
"sequence": 14,
"access": 14,
"id": 14
},
{
"isSelected": false,
"cities": [],
"name": "Illinois",
"code": "IL",
"sequence": 15,
"access": 15,
"id": 15
},
{
"isSelected": false,
"cities": [],
"name": "Indiana",
"code": "IN",
"sequence": 16,
"access": 16,
"id": 16
},
{
"isSelected": false,
"cities": [],
"name": "Iowa",
"code": "IA",
"sequence": 17,
"access": 17,
"id": 17
},
{
"isSelected": false,
"cities": [],
"name": "Kansas",
"code": "KS",
"sequence": 18,
"access": 18,
"id": 18
},
{
"isSelected": false,
"cities": [],
"name": "Kentucky",
"code": "KY",
"sequence": 19,
"access": 19,
"id": 19
},
{
"isSelected": false,
"cities": [],
"name": "Louisiana",
"code": "LA",
"sequence": 20,
"access": 20,
"id": 20
},
{
"isSelected": false,
"cities": [],
"name": "Maine",
"code": "ME",
"sequence": 21,
"access": 21,
"id": 21
},
{
"isSelected": false,
"cities": [],
"name": "Maryland",
"code": "MD",
"sequence": 22,
"access": 22,
"id": 22
},
{
"isSelected": false,
"cities": [],
"name": "Massachusetts",
"code": "MA",
"sequence": 23,
"access": 23,
"id": 23
},
{
"isSelected": false,
"cities": [
{
"isSelected": false,
"citySequences": [
{
"systemId": 1,
"sequence": 9
}
],
"name": "MI Generic",
"code": "MIG",
"id": 1
},
{
"isSelected": false,
"citySequences": [
{
"systemId": 1,
"sequence": 10
}
],
"name": "Port Huron",
"code": "POH",
"id": 9
},
{
"isSelected": false,
"citySequences": [],
"name": "Hudson",
"code": "HUD",
"id": 31
}
],
"name": "Michigan",
"code": "MI",
"sequence": 24,
"access": 24,
"id": 24
},
{
"isSelected": false,
"cities": [],
"name": "Minnesota",
"code": "MN",
"sequence": 25,
"access": 25,
"id": 25
},
{
"isSelected": false,
"cities": [],
"name": "Mississippi",
"code": "MS",
"sequence": 26,
"access": 26,
"id": 26
},
{
"isSelected": false,
"cities": [
{
"isSelected": false,
"citySequences": [
{
"systemId": 1,
"sequence": 1
}
],
"name": "Kansas City",
"code": "KCM",
"id": 29
},
{
"isSelected": false,
"citySequences": [
{
"systemId": 1,
"sequence": 2
}
],
"name": "St Louis",
"code": "STL",
"id": 30
}
],
"name": "Missouri",
"code": "MO",
"sequence": 27,
"access": 27,
"id": 27
},
{
"isSelected": false,
"cities": [],
"name": "Montana",
"code": "MT",
"sequence": 28,
"access": 28,
"id": 28
},
{
"isSelected": false,
"cities": [],
"name": "Nebraska",
"code": "NE",
"sequence": 29,
"access": 29,
"id": 29
},
{
"isSelected": false,
"cities": [],
"name": "New Hampshire",
"code": "NH",
"sequence": 31,
"access": 31,
"id": 31
},
{
"isSelected": false,
"cities": [],
"name": "New Jersey",
"code": "NJ",
"sequence": 32,
"access": 32,
"id": 32
},
{
"isSelected": false,
"cities": [],
"name": "New Mexico",
"code": "NM",
"sequence": 33,
"access": 33,
"id": 33
},
{
"isSelected": false,
"cities": [
{
"isSelected": false,
"citySequences": [
{
"systemId": 1,
"sequence": 1
},
{
"systemId": 3,
"sequence": 1
},
{
"systemId": 4,
"sequence": 1
},
{
"systemId": 5,
"sequence": 1
}
],
"name": "New York City",
"code": "NYC",
"id": 11
},
{
"isSelected": false,
"citySequences": [
{
"systemId": 1,
"sequence": 2
},
{
"systemId": 2,
"sequence": 1
}
],
"name": "Yonkers",
"code": "NYY",
"id": 12
}
],
"name": "New York",
"code": "NY",
"sequence": 34,
"access": 34,
"id": 34
},
{
"isSelected": false,
"cities": [],
"name": "North Carolina",
"code": "NC",
"sequence": 35,
"access": 35,
"id": 36
},
{
"isSelected": false,
"cities": [],
"name": "North Dakota",
"code": "ND",
"sequence": 36,
"access": 36,
"id": 37
},
{
"isSelected": false,
"cities": [
{
"isSelected": false,
"citySequences": [
{
"systemId": 1,
"sequence": 12
},
{
"systemId": 3,
"sequence": 3
},
{
"systemId": 4,
"sequence": 3
},
{
"systemId": 5,
"sequence": 3
}
],
"name": "OH Generic",
"code": "OHG",
"id": 13
},
{
"isSelected": false,
"citySequences": [
{
"systemId": 1,
"sequence": 1
},
{
"systemId": 3,
"sequence": 1
},
{
"systemId": 4,
"sequence": 1
},
{
"systemId": 5,
"sequence": 1
}
],
"name": "OH RITA",
"code": "OHR",
"id": 14
},
{
"isSelected": false,
"citySequences": [
{
"systemId": 1,
"sequence": 2
},
{
"systemId": 3,
"sequence": 2
},
{
"systemId": 4,
"sequence": 2
},
{
"systemId": 5,
"sequence": 2
}
],
"name": "OH CCA",
"code": "CCA",
"id": 15
},
{
"isSelected": false,
"citySequences": [
{
"systemId": 1,
"sequence": 3
}
],
"name": "Akron",
"code": "AKR",
"id": 16
},
{
"isSelected": false,
"citySequences": [
{
"systemId": 1,
"sequence": 4
}
],
"name": "Cincinnati",
"code": "CIN",
"id": 17
},
{
"isSelected": false,
"citySequences": [
{
"systemId": 1,
"sequence": 6
}
],
"name": "Columbus",
"code": "COL",
"id": 19
},
{
"isSelected": false,
"citySequences": [
{
"systemId": 1,
"sequence": 7
}
],
"name": "Toledo",
"code": "TOL",
"id": 20
},
{
"isSelected": false,
"citySequences": [
{
"systemId": 1,
"sequence": 8
}
],
"name": "Springfield",
"code": "SPR",
"id": 21
},
{
"isSelected": false,
"citySequences": [
{
"systemId": 1,
"sequence": 9
}
],
"name": "Wyoming",
"code": "WYO",
"id": 22
},
{
"isSelected": false,
"citySequences": [
{
"systemId": 1,
"sequence": 10
}
],
"name": "Indian_Hill",
"code": "IHL",
"id": 23
},
{
"isSelected": false,
"citySequences": [
{
"systemId": 1,
"sequence": 11
}
],
"name": "Mansfield",
"code": "MAN",
"id": 24
},
{
"isSelected": false,
"citySequences": [
{
"systemId": 1,
"sequence": 12
}
],
"name": "Crestline",
"code": "CRE",
"id": 25
}
],
"name": "Ohio",
"code": "OH",
"sequence": 37,
"access": 37,
"id": 38
},
{
"isSelected": false,
"cities": [],
"name": "Oklahoma",
"code": "OK",
"sequence": 38,
"access": 38,
"id": 39
},
{
"isSelected": false,
"cities": [],
"name": "Oregon",
"code": "OR",
"sequence": 39,
"access": 39,
"id": 40
},
{
"isSelected": false,
"cities": [
{
"isSelected": false,
"citySequences": [
{
"systemId": 1,
"sequence": 1
}
],
"name": "PA Generic",
"code": "PAG",
"id": 26
},
{
"isSelected": false,
"citySequences": [
{
"systemId": 1,
"sequence": 2
},
{
"systemId": 2,
"sequence": 1
},
{
"systemId": 3,
"sequence": 1
},
{
"systemId": 4,
"sequence": 1
},
{
"systemId": 5,
"sequence": 1
}
],
"name": "Philadelphia",
"code": "PHI",
"id": 27
}
],
"name": "Pennsylvania",
"code": "PA",
"sequence": 40,
"access": 40,
"id": 41
},
{
"isSelected": false,
"cities": [],
"name": "Rhode Island",
"code": "RI",
"sequence": 41,
"access": 41,
"id": 42
},
{
"isSelected": false,
"cities": [],
"name": "South Carolina",
"code": "SC",
"sequence": 42,
"access": 42,
"id": 43
},
{
"isSelected": false,
"cities": [],
"name": "Tennessee",
"code": "TN",
"sequence": 44,
"access": 44,
"id": 45
},
{
"isSelected": false,
"cities": [],
"name": "Texas",
"code": "TX",
"sequence": 45,
"access": 45,
"id": 46
},
{
"isSelected": false,
"cities": [],
"name": "Utah",
"code": "UT",
"sequence": 46,
"access": 46,
"id": 47
},
{
"isSelected": false,
"cities": [],
"name": "Vermont",
"code": "VT",
"sequence": 47,
"access": 47,
"id": 48
},
{
"isSelected": false,
"cities": [],
"name": "Virginia",
"code": "VA",
"sequence": 48,
"access": 48,
"id": 49
},
{
"isSelected": false,
"cities": [],
"name": "West Virginia",
"code": "WV",
"sequence": 50,
"access": 50,
"id": 51
},
{
"isSelected": false,
"cities": [],
"name": "Wisconsin",
"code": "WI",
"sequence": 51,
"access": 51,
"id": 52
}
]
Second JSON:
addedStates = [
{
"StateName": "DISTRICT_OF_COLUMBIA",
"Cities": []
},
{
"StateName": "COLORADO",
"Cities": []
},
{
"StateName": "ALABAMA",
"Cities": []
},
{
"StateName": "OHIO",
"Cities": [
{
"CityName": "AKRON"
},
{
"CityName": "CINCINNATI"
}
]
},
{
"StateName": "NEW_YORK",
"Cities": [
{
"CityName": "YONKERS"
}
]
}
]
After filtering first JSON with second JSON I expect this:
result = [
{
"isSelected": false,
"cities": [],
"name": "Alabama",
"code": "AL",
"sequence": 2,
"access": 2,
"id": 2
},
{
"isSelected": false,
"cities": [],
"name": "Colorado",
"code": "CO",
"sequence": 7,
"access": 7,
"id": 7
},
{
"isSelected": false,
"cities": [],
"name": "District of Columbia",
"code": "DC",
"sequence": 10,
"access": 10,
"id": 10
},
{
"isSelected": false,
"cities": [
{
"isSelected": false,
"citySequences": [
{
"systemId": 1,
"sequence": 2
},
{
"systemId": 2,
"sequence": 1
}
],
"name": "Yonkers",
"code": "NYY",
"id": 12
}
],
"name": "New York",
"code": "NY",
"sequence": 34,
"access": 34,
"id": 34
},
{
"isSelected": false,
"cities": [
{
"isSelected": false,
"citySequences": [
{
"systemId": 1,
"sequence": 3
}
],
"name": "Akron",
"code": "AKR",
"id": 16
},
{
"isSelected": false,
"citySequences": [
{
"systemId": 1,
"sequence": 4
}
],
"name": "Cincinnati",
"code": "CIN",
"id": 17
}
],
"name": "Ohio",
"code": "OH",
"sequence": 37,
"access": 37,
"id": 38
}
]