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)
Related
I'm making a fetch to the API to grab the total number of players, the returned data is below:
"data": [
{
"id": 558,
"first_name": "Dave",
"height_feet": null,
"height_inches": null,
"last_name": "Jamerson",
"position": "",
"team": {
"id": 11,
"abbreviation": "HOU",
"city": "Houston",
"conference": "West",
"division": "Southwest",
"full_name": "Houston Rockets",
"name": "Rockets"
},
"weight_pounds": null
},
{
"id": 559,
"first_name": "Scott",
"height_feet": null,
"height_inches": null,
"last_name": "Brooks",
"position": "",
"team": {
"id": 18,
"abbreviation": "MIN",
"city": "Minnesota",
"conference": "West",
"division": "Northwest",
"full_name": "Minnesota Timberwolves",
"name": "Timberwolves"
},
"weight_pounds": null
},
{
"id": 560,
"first_name": "Rolando",
"height_feet": null,
"height_inches": null,
"last_name": "Blackman",
"position": "",
"team": {
"id": 7,
"abbreviation": "DAL",
"city": "Dallas",
"conference": "West",
"division": "Southwest",
"full_name": "Dallas Mavericks",
"name": "Mavericks"
},
"weight_pounds": null
},
{
"id": 561,
"first_name": "Avery",
"height_feet": null,
"height_inches": null,
"last_name": "Johnson",
"position": "",
"team": {
"id": 8,
"abbreviation": "DEN",
"city": "Denver",
"conference": "West",
"division": "Northwest",
"full_name": "Denver Nuggets",
"name": "Nuggets"
},
"weight_pounds": null
},
{
"id": 562,
"first_name": "Rod",
"height_feet": null,
"height_inches": null,
"last_name": "Higgins",
"position": "",
"team": {
"id": 10,
"abbreviation": "GSW",
"city": "Golden State",
"conference": "West",
"division": "Pacific",
"full_name": "Golden State Warriors",
"name": "Warriors"
},
"weight_pounds": null
},
{
"id": 566,
"first_name": "Sam",
"height_feet": null,
"height_inches": null,
"last_name": "Vincent",
"position": "",
"team": {
"id": 22,
"abbreviation": "ORL",
"city": "Orlando",
"conference": "East",
"division": "Southeast",
"full_name": "Orlando Magic",
"name": "Magic"
},
"weight_pounds": null
},
{
"id": 567,
"first_name": "Isiah",
"height_feet": null,
"height_inches": null,
"last_name": "Thomas",
"position": "",
"team": {
"id": 9,
"abbreviation": "DET",
"city": "Detroit",
"conference": "East",
"division": "Central",
"full_name": "Detroit Pistons",
"name": "Pistons"
},
"weight_pounds": null
}
],
"meta": {
"total_pages": 39,
"current_page": 1,
"next_page": 2,
"per_page": 100,
"total_count": 3828
}
Problem is, the API only allows for a max of 100 results. As you can see in the "meta" object at the bottom, there is a total_count of 3828 and 39 pages, how would I access the other pages and get all 3828 results? currently I only get the first page with 100 results when I fetch.
const getPlayers = () => {
fetch(`https://www.balldontlie.io/api/v1/players?per_page=100`)
.then(res => res.json())
.then(data => dispatch(playerActions.getPlayers(data)));
}
I am having an array like this
[
{
"id": "Client 1",
"mName": "SDk",
"cName": "Thor Odin",
"gName": "",
"gAmt": 80000,
"gls": 2,
"value": 0.855,
"date": "22/1/2022",
"income": "",
"subRows": [
{
"id": "goal-1",
"cName": "",
"mName": "",
"gName": "Retirement1",
"gAmt": 10000,
"gls": 1,
"income": "60/40",
"date": "22/1/2022",
"value": 0.99
},
{
"id": "goal-2",
"cName": "",
"mName": "",
"gName": "Save For Child Education",
"gAmt": 70000,
"gls": 1,
"income": "55/45",
"date": "5/12/2023",
"value": 0.72
}
]
},
{
"id": "Client 2",
"mName": "SDk",
"cName": "Steve Rogers",
"gName": "Save for Investment",
"gAmt": 67000,
"gls": 1,
"value": 0.7,
"date": "22/1/2022",
"income": "60/40"
},
{
"id": "Client 3",
"mName": "Pal",
"cName": "Wanda Vision",
"gls": 0,
"value": 0.9,
"date": "",
"income": ""
},
{
"id": "Client 4",
"mName": "Pal",
"cName": "Tony Stark",
"gName": "",
"gAmt": 23500,
"gls": 2,
"value": 0.29,
"date": "27/10/2019",
"income": "",
"subRows": [
{
"id": "goal-4",
"cName": "",
"mName": "",
"gName": "Education Loan",
"gAmt": 500,
"gls": 1,
"income": "60/40",
"date": "27/10/2019",
"value": 0.29
},
{
"id": "goal-5",
"cName": "",
"mName": "",
"gName": "House Loan",
"gAmt": 23000,
"gls": 1,
"income": "30/70",
"date": "16/6/2022",
"value": 0.29
}
]
},
{
"id": "Client 5",
"mName": "Joe",
"cName": "Hack Eye",
"gName": "Save For World Tour",
"gAmt": 400000,
"gls": 1,
"value": 0.74,
"date": "",
"income": "60/40"
},
{
"id": "Client 6",
"mName": "Joe",
"cName": "Nick Fury",
"gName": "",
"gAmt": 51070,
"gls": 2,
"value": 0.44499999999999995,
"date": "9/3/2022",
"income": "",
"subRows": [
{
"id": "goal-7",
"cName": "",
"mName": "",
"gName": "To Build A Workspace",
"gAmt": 42340,
"gls": 1,
"income": "60/40",
"date": "9/3/2022",
"value": 0.6
},
{
"id": "goal-8",
"cName": "",
"mName": "",
"gName": "Cloud Examination",
"gAmt": 8730,
"gls": 1,
"income": "30/70",
"date": "9/11/2021",
"value": 0.29
}
]
}
]
And I need to convert the above array into like this
[
{
"mName": "SDk",
"id": "",
"cName": "",
"gName": "",
"gAmt": "",
"gls": "",
"value": "",
"date": "",
"income": "",
"subRows": [
{
"mName": "",
"id": "Client 1",
"cName": "Thor Odin",
"gName": "",
"gAmt": 80000,
"gls": 2,
"value": 0.855,
"date": "22/1/2022",
"income": "",
"subRows": [
{
"id": "goal-1",
"cName": "",
"mName": "",
"gName": "Retirement1",
"gAmt": 10000,
"gls": 1,
"income": "60/40",
"date": "22/1/2022",
"value": 0.99
},
{
"id": "goal-2",
"cName": "",
"mName": "",
"gName": "Save For Child Education",
"gAmt": 70000,
"gls": 1,
"income": "55/45",
"date": "5/12/2023",
"value": 0.72
}
]
},
{
"mName": "",
"id": "Client 2",
"cName": "Steve Rogers",
"gName": "Save for Investment",
"gAmt": 67000,
"gls": 1,
"value": 0.7,
"date": "22/1/2022",
"income": "60/40"
},
{
"mName": "",
"id": "Client 3",
"cName": "Wanda Vision",
"gls": 0,
"value": 0.9,
"date": "",
"income": ""
},
{
"mName": "",
"id": "Client 4",
"cName": "Tony Stark",
"gName": "",
"gAmt": 23500,
"gls": 2,
"value": 0.29,
"date": "27/10/2019",
"income": "",
"subRows": [
{
"id": "goal-4",
"cName": "",
"mName": "",
"gName": "Education Loan",
"gAmt": 500,
"gls": 1,
"income": "60/40",
"date": "27/10/2019",
"value": 0.29
},
{
"id": "goal-5",
"cName": "",
"mName": "",
"gName": "House Loan",
"gAmt": 23000,
"gls": 1,
"income": "30/70",
"date": "16/6/2022",
"value": 0.29
}
]
}
]
},
{
"mName": "Joe",
"id": "",
"cName": "",
"gName": "",
"gAmt": "",
"gls": "",
"value": "",
"date": "",
"income": "",
"subRows": [
{
"mName": "",
"id": "Client 5",
"cName": "Hack Eye",
"gName": "Save For World Tour",
"gAmt": 400000,
"gls": 1,
"value": 0.74,
"date": "",
"income": "60/40"
},
{
"mName": "",
"id": "Client 6",
"cName": "Nick Fury",
"gName": "",
"gAmt": 51070,
"gls": 2,
"value": 0.44499999999999995,
"date": "9/3/2022",
"income": "",
"subRows": [
{
"id": "goal-7",
"cName": "",
"mName": "",
"gName": "To Build A Workspace",
"gAmt": 42340,
"gls": 1,
"income": "60/40",
"date": "9/3/2022",
"value": 0.6
},
{
"id": "goal-8",
"cName": "",
"mName": "",
"gName": "Cloud Examination",
"gAmt": 8730,
"gls": 1,
"income": "30/70",
"date": "9/11/2021",
"value": 0.29
}
]
},
{
"mName": "",
"id": "Client 7",
"cName": "Star Lord",
"gName": "Save For Child Education",
"gAmt": 400000,
"gls": 1,
"value": 0.93,
"date": "",
"income": "55/45"
}
]
},
{
"mName": "Pal",
"id": "",
"cName": "",
"gName": "",
"gAmt": "",
"gls": "",
"value": "",
"date": "",
"income": "",
"subRows": [
{
"mName": "",
"id": "Client 8",
"cName": "Thanos",
"gName": "",
"gAmt": 1200000,
"gls": 3,
"value": 0.29,
"date": "2/11/2019",
"income": "",
"subRows": [
{
"id": "goal-10",
"cName": "",
"mName": "",
"gName": "Relocation Expense Goal",
"gAmt": 400000,
"gls": 1,
"income": "22/78",
"date": "2/11/2019",
"value": 0.29
},
{
"id": "goal-11",
"cName": "",
"mName": "",
"gName": "Save for to buy bike",
"gAmt": 400000,
"gls": 1,
"income": "50/50",
"date": "1/1/2020",
"value": 0.29
},
{
"id": "goal-12",
"cName": "",
"mName": "",
"gName": "Save For Education",
"gAmt": 400000,
"gls": 1,
"income": "65/35",
"date": "9/5/2022",
"value": 0.29
}
]
},
{
"mName": "",
"id": "Client 9",
"cName": "Ego",
"gName": "Save For Education",
"gAmt": 400000,
"gls": 1,
"value": 0.72,
"date": "",
"income": "65/35"
},
{
"mName": "",
"id": "Client 10",
"cName": "Bruce Banner",
"gName": "",
"gAmt": 27600,
"gls": 2,
"value": 0.975,
"date": "9/10/2018",
"income": "",
"subRows": [
{
"id": "goal-14",
"cName": "",
"mName": "",
"gName": "Car Loan",
"gAmt": 23000,
"gls": 1,
"income": "60/40",
"date": "9/10/2018",
"value": 0.99
},
{
"id": "goal-15",
"cName": "",
"mName": "",
"gName": "Bike Loan",
"gAmt": 4600,
"gls": 1,
"income": "30/70",
"date": "9/11/2021",
"value": 0.96
}
]
}
]
}
]
grouping the array using mName. This below function is working fine on converting the provided array of objects.
const data = [{"id":"Client 1","mName":"SDk","cName":"Thor Odin","gName":"","gAmt":80000,"gls":2,"value":0.855,"date":"22/1/2022","income":"","subRows":[{"id":"goal-1","cName":"","mName":"","gName":"Retirement1","gAmt":10000,"gls":1,"income":"60/40","date":"22/1/2022","value":0.99},{"id":"goal-2","cName":"","mName":"","gName":"Save For Child Education","gAmt":70000,"gls":1,"income":"55/45","date":"5/12/2023","value":0.72}]},{"id":"Client 2","mName":"SDk","cName":"Steve Rogers","gName":"Save for Investment","gAmt":67000,"gls":1,"value":0.7,"date":"22/1/2022","income":"60/40"},{"id":"Client 3","mName":"SDk","cName":"Wanda Vision","gls":0,"value":0.9,"date":"","income":""},{"id":"Client 4","mName":"SDk","cName":"Tony Stark","gName":"","gAmt":23500,"gls":2,"value":0.29,"date":"27/10/2019","income":"","subRows":[{"id":"goal-4","cName":"","mName":"","gName":"Education Loan","gAmt":500,"gls":1,"income":"60/40","date":"27/10/2019","value":0.29},{"id":"goal-5","cName":"","mName":"","gName":"House Loan","gAmt":23000,"gls":1,"income":"30/70","date":"16/6/2022","value":0.29}]},{"id":"Client 5","mName":"Joe","cName":"Hack Eye","gName":"Save For World Tour","gAmt":400000,"gls":1,"value":0.74,"date":"","income":"60/40"},{"id":"Client 6","mName":"Joe","cName":"Nick Fury","gName":"","gAmt":51070,"gls":2,"value":0.44499999999999995,"date":"9/3/2022","income":"","subRows":[{"id":"goal-7","cName":"","mName":"","gName":"To Build A Workspace","gAmt":42340,"gls":1,"income":"60/40","date":"9/3/2022","value":0.6},{"id":"goal-8","cName":"","mName":"","gName":"Cloud Examination","gAmt":8730,"gls":1,"income":"30/70","date":"9/11/2021","value":0.29}]},{"id":"Client 7","mName":"Joe","cName":"Star Lord","gName":"Save For Child Education","gAmt":400000,"gls":1,"value":0.93,"date":"","income":"55/45"},{"id":"Client 8","mName":"Pal","cName":"Thanos","gName":"","gAmt":1200000,"gls":3,"value":0.29,"date":"2/11/2019","income":"","subRows":[{"id":"goal-10","cName":"","mName":"","gName":"Relocation Expense Goal","gAmt":400000,"gls":1,"income":"22/78","date":"2/11/2019","value":0.29},{"id":"goal-11","cName":"","mName":"","gName":"Save for to buy bike","gAmt":400000,"gls":1,"income":"50/50","date":"1/1/2020","value":0.29},{"id":"goal-12","cName":"","mName":"","gName":"Save For Education","gAmt":400000,"gls":1,"income":"65/35","date":"9/5/2022","value":0.29}]},{"id":"Client 9","mName":"Pal","cName":"Ego","gName":"Save For Education","gAmt":400000,"gls":1,"value":0.72,"date":"","income":"65/35"},{"id":"Client 10","mName":"Pal","cName":"Bruce Banner","gName":"","gAmt":27600,"gls":2,"value":0.975,"date":"9/10/2018","income":"","subRows":[{"id":"goal-14","cName":"","mName":"","gName":"Car Loan","gAmt":23000,"gls":1,"income":"60/40","date":"9/10/2018","value":0.99},{"id":"goal-15","cName":"","mName":"","gName":"Bike Loan","gAmt":4600,"gls":1,"income":"30/70","date":"9/11/2021","value":0.96}]}]
const arrExpected = data.reduce((acc,row) =>
{
if (row.mName !== acc.level1.cName)
{
let newRow1 = { mName:row.mName, id: '', cName: '', gName: '',gAmt:'',gls:'',value:'',date:'',income:'', subRows:[] }
acc.result.push( newRow1 )
acc.level1.cName = row.mName
acc.level1.arr = newRow1.subRows
}
let newRow2 = { mName: '',id: row.id, cName: row.cName, gName: row.gName, gAmt: row.gAmt, gls: row.gls, value:row.value, date: row.date, income: row.income}
if (row.subRows)
{
acc.level2.arr = newRow2.subRows = []
}
acc.level1.arr.push( newRow2 )
if (row.subRows)
{
row.subRows.forEach( subRow =>
{
acc.level2.arr.push( {...subRow})
})
}
return acc
}
, { result:[], level1:{cName:'',arr:null}, level2:{arr:null}}
).result;
console.log(JSON.stringify(arrExpected) )
But the above function is quite complicated to understand. If a new person takes over the code means it's hard to know what it is doing.
Is any way this function can be simplified? Please let me know the feasibility of this one.
And why I am doing this kind of structure because. I am in creating a multi-level expandable table row using #tanstack/react-table. For that, It requires structure like this.
Here u can get the working demo example of this https://codesandbox.io/s/tanstack-table-expansion-sub-level-goe-191pip?file=/src/App.js
Below question is based on the answer for further improvements:
Dynamic Key Passing
I could able to pass the key upto the first level of the function.
Usind this
let dynamicKey = 'managerName'
const groupsByMangerName = data.reduce((acc, item) => {
acc[item[dynamicKey]] ??= [];
acc[item[dynamicKey]].push({ ...item, [dynamicKey]: "" });
return acc;
}, {});
But not able to pass this into the below section:
const arrExpected = Object.entries(groupsByMName)
.map(([mName, subRows]) => ({ ...emptyNode, mName, subRows }));
To decrease amount of code and improve understanding, you can take the following approach
// const data = [ big array of objects ];
const emptyNode = {
mName: "",
id: "",
cName: "",
gName: "",
gAmt: "",
gls: "",
value: "",
date: "",
income: "",
subRows: [],
};
const groupsByMName = data.reduce((acc, item) => {
acc[item.mName] ??= [];
acc[item.mName].push({ ...item, mName: "" });
return acc;
}, {});
const arrExpected = Object.entries(groupsByMName)
.map(([mName, subRows]) => ({ ...emptyNode, mName, subRows }));
I am trying to compare two arrays but it is not filtering correctly. I am trying to add users, my function compares the ID and StaffID and if the StaffID is not in the current user array it should set the state of new user so they can be added.
export default function AddUserDropdown({onChange}) {
useEffect(() => {
getUsersToAdd();
}, []);
const [state, setState] = React.useState({
open: false,
name: '',
users: [],
id: null,
});
const [user, setUser] = React.useState({
newUsers: []
})
const getUsersToAdd = () => {
axios.all([
axios.get('/updateUserList'),
axios.get('/userInformation')
])
.then(axios.spread((newUserBox, currentUserBox) => {
let newUserIds = [];
let currentUserIds = [];
for (let newUser of currentUserBox.data){
newUserIds.push(newUser.id);
}
for (let user of newUserBox.data) {
if (!newUserIds[user.staffID]) {
currentUserIds.push(user);
}
}
setUser({...user, newUsers: currentUserIds });
}));
}
// ...
};
// ...
};
When the axios calls request userinformation endpoint it returns this
[
{
"id": 1,
"firstName": "Elton",
"lastName": "Frederick",
"departmentId": 1,
"admin": true,
"hasApproval": false,
"position": "Developer",
"vh5given": 31,
"vh5rec": 280,
"profilePic": "https://www.travelplannersinternational.com/wp-content/uploads/2019/12/Elton.jpg",
"password": "abc234"
},
{
"id": 2,
"firstName": "Julio",
"lastName": "Probando",
"departmentId": 1,
"admin": false,
"hasApproval": true,
"position": "Lead Dev",
"vh5given": 11,
"vh5rec": 339,
"profilePic": "https://388616.smushcdn.com/941012/wp-content/uploads/2019/03/Julio_.jpg?lossy=1&strip=1&webp=1",
"password": "abc232"
},
{
"id": 3,
"firstName": "Corey",
"lastName": "Chris",
"departmentId": 2,
"admin": false,
"hasApproval": false,
"position": "Customer Service",
"vh5given": 14,
"vh5rec": 167,
"profilePic": "https://388616.smushcdn.com/941012/wp-content/uploads/2019/09/Corey.jpg?lossy=1&strip=1&webp=1",
"password": "abc123"
},
{
"id": 4,
"firstName": "Daisy",
"lastName": "Ramos",
"departmentId": 3,
"admin": false,
"hasApproval": false,
"position": "ATC",
"vh5given": 22,
"vh5rec": 202,
"profilePic": "https://388616.smushcdn.com/941012/wp-content/uploads/2019/03/Daisy_.jpg?lossy=1&strip=1&webp=1",
"password": "abc321"
},
{
"id": 7,
"firstName": "Air Car Hotel",
"lastName": "Nunca",
"departmentId": 4,
"admin": false,
"hasApproval": false,
"position": "",
"vh5given": 0,
"vh5rec": 25,
"profilePic": "profile.jpg",
"password": "abc123"
},
{
"id": 8,
"firstName": "Jenn",
"lastName": "Lee",
"departmentId": 4,
"admin": false,
"hasApproval": false,
"position": "Vp Of Sales",
"vh5given": 0,
"vh5rec": 0,
"profilePic": "https://388616.smushcdn.com/941012/wp-content/uploads/2019/03/Jenn2_.jpg?lossy=1&strip=1&webp=1",
"password": "abc123"
},
{
"id": 9,
"firstName": "Reyna",
"lastName": "Pagan",
"departmentId": 5,
"admin": false,
"hasApproval": false,
"position": "Agent Support Manager",
"vh5given": 0,
"vh5rec": 20,
"profilePic": "https://388616.smushcdn.com/941012/wp-content/uploads/2019/03/Reyna_.jpg?lossy=1&strip=1&webp=1",
"password": "abc123"
},
{
"id": 10,
"firstName": "Ameilia",
"lastName": "Rodriguez",
"departmentId": 6,
"admin": false,
"hasApproval": false,
"position": "Human Resources",
"vh5given": 0,
"vh5rec": 5,
"profilePic": "https://388616.smushcdn.com/941012/wp-content/uploads/2019/03/Amelia_.jpg?lossy=1&strip=1&webp=1",
"password": "abc123"
}
]
These are the users that have been added.
When the updateUserList endpoint is called it returns:
[
{
"staffID": 1,
"dept": "Junior Web Developer",
"email": "manasaN#tpionline.com",
"name": "manasa",
"password": "$2y$10$/zYS7OhzwdLOi6Slzc3Rv.aJFJALiY0y1J6MjnLCN24GmZ3rMHWUS"
},
{
"staffID": 2,
"dept": "Web Developer",
"email": "juliof#tpionline.net",
"name": "Julio Fajardo",
"password": "$2y$10$MphAC8aRY2uzs1ZERZDn9uvCqK1/1nd7t0KukEkvGbx5Y4van.Da6"
},
{
"staffID": 3,
"dept": "Fake Title",
"email": "johnf#tpionline.com",
"name": "John Fester",
"password": "$2y$10$/oa/ESQmhhc5WvxrQKoUU.Pj5sM3gZY5FccilGfCUL5eyeOU5IDSa"
},
{
"staffID": 5,
"dept": "Fake Title",
"email": "fakeguy#gmail.net",
"name": "Test",
"password": "$2y$10$VWnnw5gRTN2absWos04fsOixW6TjOepNa3n0v/7ybFqsFZL8oPiJm"
},
{
"staffID": 6,
"dept": "Conf room",
"email": "conf2#gmail.com",
"name": "Conf 1st floor",
"password": "$2y$10$KAZa1k2Sd/rg6dnVeqw4duB/XbAhcVXP.Fze6Zle3ZhcMaRphloG."
},
{
"staffID": 8,
"dept": "Fake Title",
"email": "newguy#gmail.net",
"name": "New guy",
"password": ""
},
{
"staffID": 9,
"dept": "Fake Title",
"email": "nguy#gmail.net",
"name": "New Guy2",
"password": ""
},
{
"staffID": 12,
"dept": "Test ADD",
"email": "cristinab#tpionline.com",
"name": "Cristina Bermudez",
"password": "$2y$10$92I6fSJY6OW001caJJmeReHnaeF5tdHBjWHBmoCvX1RnfhTspjpBa"
},
{
"staffID": 30,
"dept": "Erwing",
"email": "erwingh#tpionline.com",
"name": "Erwing Hernandez",
"password": "$2y$10$RWgOBbUHojgmyk3behYhd.kzdFEiH.6BBaxn4B070pS5q5Gf3ZYEa"
}
]
What I need to accomplish is that if the there is no current user whose ID equals the staff ID it should be set in the state so i can add this user. With the data above the users that should be added should be
have the staff ID of: 5, 6, 12,30.
Right Now My functions returns:
0: {staffID: 8, dept: "Fake Title", email: "newguy#gmail.net", name: "New guy", password: ""}
1: {staffID: 9, dept: "Fake Title", email: "nguy#gmail.net", name: "New Guy2", password: ""}
2: {staffID: 12, dept: "Test ADD", email: "cristinab#tpionline.com", name: "Cristina Bermudez", password: "$2y$10$92I6fSJY6OW001caJJmeReHnaeF5tdHBjWHBmoCvX1RnfhTspjpBa"}
3: {staffID: 30, dept: "Erwing", email: "erwingh#tpionline.com", name: "Erwing Hernandez", password: "$2y$10$RWgOBbUHojgmyk3behYhd.kzdFEiH.6BBaxn4B070pS5q5Gf3ZYEa"}
let currentUserIds = currentUserBox.map(user => user.id)
let newUsers = newUserBox.filter(newUser => !currentUserIds.includes(newUser.staffID))
newUsers is the array you want.
The code would look something like this:
let currentUserBox = [{
"id": 1,
"firstName": "Elton",
"lastName": "Frederick",
"departmentId": 1,
"admin": true,
"hasApproval": false,
"position": "Developer",
"vh5given": 31,
"vh5rec": 280,
"profilePic": "https://www.travelplannersinternational.com/wp-content/uploads/2019/12/Elton.jpg",
"password": "abc234"
},
{
"id": 2,
"firstName": "Julio",
"lastName": "Probando",
"departmentId": 1,
"admin": false,
"hasApproval": true,
"position": "Lead Dev",
"vh5given": 11,
"vh5rec": 339,
"profilePic": "https://388616.smushcdn.com/941012/wp-content/uploads/2019/03/Julio_.jpg?lossy=1&strip=1&webp=1",
"password": "abc232"
},
{
"id": 3,
"firstName": "Corey",
"lastName": "Chris",
"departmentId": 2,
"admin": false,
"hasApproval": false,
"position": "Customer Service",
"vh5given": 14,
"vh5rec": 167,
"profilePic": "https://388616.smushcdn.com/941012/wp-content/uploads/2019/09/Corey.jpg?lossy=1&strip=1&webp=1",
"password": "abc123"
},
{
"id": 4,
"firstName": "Daisy",
"lastName": "Ramos",
"departmentId": 3,
"admin": false,
"hasApproval": false,
"position": "ATC",
"vh5given": 22,
"vh5rec": 202,
"profilePic": "https://388616.smushcdn.com/941012/wp-content/uploads/2019/03/Daisy_.jpg?lossy=1&strip=1&webp=1",
"password": "abc321"
},
{
"id": 7,
"firstName": "Air Car Hotel",
"lastName": "Nunca",
"departmentId": 4,
"admin": false,
"hasApproval": false,
"position": "",
"vh5given": 0,
"vh5rec": 25,
"profilePic": "profile.jpg",
"password": "abc123"
},
{
"id": 8,
"firstName": "Jenn",
"lastName": "Lee",
"departmentId": 4,
"admin": false,
"hasApproval": false,
"position": "Vp Of Sales",
"vh5given": 0,
"vh5rec": 0,
"profilePic": "https://388616.smushcdn.com/941012/wp-content/uploads/2019/03/Jenn2_.jpg?lossy=1&strip=1&webp=1",
"password": "abc123"
},
{
"id": 9,
"firstName": "Reyna",
"lastName": "Pagan",
"departmentId": 5,
"admin": false,
"hasApproval": false,
"position": "Agent Support Manager",
"vh5given": 0,
"vh5rec": 20,
"profilePic": "https://388616.smushcdn.com/941012/wp-content/uploads/2019/03/Reyna_.jpg?lossy=1&strip=1&webp=1",
"password": "abc123"
},
{
"id": 10,
"firstName": "Ameilia",
"lastName": "Rodriguez",
"departmentId": 6,
"admin": false,
"hasApproval": false,
"position": "Human Resources",
"vh5given": 0,
"vh5rec": 5,
"profilePic": "https://388616.smushcdn.com/941012/wp-content/uploads/2019/03/Amelia_.jpg?lossy=1&strip=1&webp=1",
"password": "abc123"
}
]
let newUserBox = [{
"staffID": 1,
"dept": "Junior Web Developer",
"email": "manasaN#tpionline.com",
"name": "manasa",
"password": "$2y$10$/zYS7OhzwdLOi6Slzc3Rv.aJFJALiY0y1J6MjnLCN24GmZ3rMHWUS"
},
{
"staffID": 2,
"dept": "Web Developer",
"email": "juliof#tpionline.net",
"name": "Julio Fajardo",
"password": "$2y$10$MphAC8aRY2uzs1ZERZDn9uvCqK1/1nd7t0KukEkvGbx5Y4van.Da6"
},
{
"staffID": 3,
"dept": "Fake Title",
"email": "johnf#tpionline.com",
"name": "John Fester",
"password": "$2y$10$/oa/ESQmhhc5WvxrQKoUU.Pj5sM3gZY5FccilGfCUL5eyeOU5IDSa"
},
{
"staffID": 5,
"dept": "Fake Title",
"email": "fakeguy#gmail.net",
"name": "Test",
"password": "$2y$10$VWnnw5gRTN2absWos04fsOixW6TjOepNa3n0v/7ybFqsFZL8oPiJm"
},
{
"staffID": 6,
"dept": "Conf room",
"email": "conf2#gmail.com",
"name": "Conf 1st floor",
"password": "$2y$10$KAZa1k2Sd/rg6dnVeqw4duB/XbAhcVXP.Fze6Zle3ZhcMaRphloG."
},
{
"staffID": 8,
"dept": "Fake Title",
"email": "newguy#gmail.net",
"name": "New guy",
"password": ""
},
{
"staffID": 9,
"dept": "Fake Title",
"email": "nguy#gmail.net",
"name": "New Guy2",
"password": ""
},
{
"staffID": 12,
"dept": "Test ADD",
"email": "cristinab#tpionline.com",
"name": "Cristina Bermudez",
"password": "$2y$10$92I6fSJY6OW001caJJmeReHnaeF5tdHBjWHBmoCvX1RnfhTspjpBa"
},
{
"staffID": 30,
"dept": "Erwing",
"email": "erwingh#tpionline.com",
"name": "Erwing Hernandez",
"password": "$2y$10$RWgOBbUHojgmyk3behYhd.kzdFEiH.6BBaxn4B070pS5q5Gf3ZYEa"
}
]
let currentUserIds = currentUserBox.map(user => user.id)
let newUsers = newUserBox.filter(newUser => !currentUserIds.includes(newUser.staffID))
console.log(newUsers)
I would like to show you some example how to do it:
const array1 = [{
"id": 1,
"firstName": "One"
},
{
"id": 3,
"firstName": "Three"
},
{
"id": 5,
"firstName": "Five"
}
];
const array2 = [{
"staffID": 2,
"firstName": "Staff Two"
},
{
"staffID": 3,
"firstName": "Staff Three"
},
{
"staffID": 4,
"firstName": "Staff Four"
},
{
"staffID": 7,
"firstName": "Staff Seven"
}
];
const filtered = array1.filter(one => array2.filter(two => one.id !== two.staffID).length > 0);
console.log(filtered);
Currently have an array of objects which contain game releases. However game releases can happen on multiple platforms and these appear as separate objects within the array. I'm looking to remove duplicate games by comparing the game id but merge the platforms object
I have tried using the reduce function which successfully removes duplicate objects by game id but I'm unable to adapt this to merge platforms
const filteredArr = data.reduce((acc, current) => {
const x = acc.find(item => item.game.id === current.game.id);
if (!x) {
return acc.concat([current]);
} else {
return acc;
}
}, []);
Current Array:
const data = [{
"id": 157283,
"date": 1553212800,
"game": {
"id": 76882,
"name": "Sekiro: Shadows Die Twice",
"popularity": 41.39190295640344
},
"human": "2019-Mar-22",
"m": 3,
"platform": {"id": 48, "name": "PlayStation 4"},
"region": 8,
"y": 2019
}, {
"id": 12,
"date": 1553212800,
"game": {
"id": 76832,
"name": "Spiderman",
"popularity": 41.39190295640344
},
"human": "2019-Mar-22",
"m": 3,
"platform": {"id": 6, "name": "PC (Microsoft Windows)"},
"region": 8,
"y": 2019
}, {
"id": 157283,
"date": 1553212800,
"game": {
"id": 76882,
"name": "Sekiro: Shadows Die Twice",
"popularity": 41.39190295640344
},
"human": "2019-Mar-22",
"m": 3,
"platform": {"id": 48, "name": "Xbox"},
"region": 8,
"y": 2019
}]
Expected format after merge:
[{
"id": 157283,
"date": 1553212800,
"game": {
"id": 76882,
"name": "Sekiro: Shadows Die Twice",
"popularity": 41.39190295640344
},
"human": "2019-Mar-22",
"m": 3,
"platforms": ["PlayStation", "Xbox"],
"region": 8,
"y": 2019
}, {
"id": 12,
"date": 1553212800,
"game": {
"id": 76832,
"name": "Spiderman",
"popularity": 41.39190295640344
},
"human": "2019-Mar-22",
"m": 3,
"platforms": ["Playstation"],
"region": 8,
"y": 2019
}]
You were really close, you just need to change the logic a bit. You can try something like the following; an example - https://repl.it/#EQuimper/ScaryBumpyCircle
const filteredArr = data.reduce((acc, current) => {
const x = acc.find(item => item.game.id === current.game.id);
if (!x) {
current.platform = [current.platform]
acc.push(current);
} else {
x.platform.push(current.platform);
}
return acc;
}, []);
The return value is
[
{
"id": 157283,
"date": 1553212800,
"game": {
"id": 76882,
"name": "Sekiro: Shadows Die Twice",
"popularity": 41.39190295640344
},
"human": "2019-Mar-22",
"m": 3,
"platform": [
{
"id": 48,
"name": "PlayStation 4"
},
{
"id": 48,
"name": "Xbox"
}
],
"region": 8,
"y": 2019
},
{
"id": 12,
"date": 1553212800,
"game": {
"id": 76832,
"name": "Spiderman",
"popularity": 41.39190295640344
},
"human": "2019-Mar-22",
"m": 3,
"platform": [
{
"id": 6,
"name": "PC (Microsoft Windows)"
}
],
"region": 8,
"y": 2019
}
]
If you want to have just an array of platform strings, go with
const filteredArr = data.reduce((acc, current) => {
const x = acc.find(item => item.game.id === current.game.id);
if (!x) {
current.platform = [current.platform.name]
acc.push(current);
} else {
x.platform.push(current.platform.name);
}
return acc;
}, []);
And now the return value is
[
{
"id": 157283,
"date": 1553212800,
"game": {
"id": 76882,
"name": "Sekiro: Shadows Die Twice",
"popularity": 41.39190295640344
},
"human": "2019-Mar-22",
"m": 3,
"platform": [
"PlayStation 4",
"Xbox"
],
"region": 8,
"y": 2019
},
{
"id": 12,
"date": 1553212800,
"game": {
"id": 76832,
"name": "Spiderman",
"popularity": 41.39190295640344
},
"human": "2019-Mar-22",
"m": 3,
"platform": [
"PC (Microsoft Windows)"
],
"region": 8,
"y": 2019
}
]
You could separate platform of the object and look if you have an object with the same id and add the platfor tho the array, of not create a new data set.
const
data = [{ id: 157283, date: 1553212800, game: { id: 76882, name: "Sekiro: Shadows Die Twice", popularity: 41.39190295640344 }, human: "2019-Mar-22", m: 3, platform: { id: 48, name: "PlayStation 4" }, region: 8, y: 2019 }, { id: 12, date: 1553212800, game: { id: 76832, name: "Spiderman", popularity: 41.39190295640344 }, human: "2019-Mar-22", m: 3, platform: { id: 6, name: "PC (Microsoft Windows)" }, region: 8, y: 2019 }, { id: 157283, date: 1553212800, game: { id: 76882, name: "Sekiro: Shadows Die Twice", popularity: 41.39190295640344 }, human: "2019-Mar-22", m: 3, platform: { id: 48, name: "Xbox" }, region: 8, y: 2019 }],
result = data.reduce((r, { platform, ...o }) => {
var temp = r.find(({ id }) => id === o.id);
if (!temp) r.push(temp = { ...o, platforms: [] });
temp.platforms.push(platform);
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Please take a look:
const data = [ { "id": 157283,
"date": 1553212800,
"game": {
"id": 76882,
"name": "Sekiro: Shadows Die Twice",
"popularity": 41.39190295640344
},
"human": "2019-Mar-22",
"m": 3,
"platform": {
"id": 48,
"name": "PlayStation 4"
},
"region": 8,
"y": 2019
},
{
"id": 12,
"date": 1553212800,
"game": {
"id": 76832,
"name": "Spiderman",
"popularity": 41.39190295640344
},
"human": "2019-Mar-22",
"m": 3,
"platform": {
"id": 6,
"name": "PC (Microsoft Windows)"
},
"region": 8,
"y": 2019
},{ "id": 157283,
"date": 1553212800,
"game": {
"id": 76882,
"name": "Sekiro: Shadows Die Twice",
"popularity": 41.39190295640344
},
"human": "2019-Mar-22",
"m": 3,
"platform": {
"id": 48,
"name": "Xbox"
},
"region": 8,
"y": 2019
},
]
const filteredArr = data.reduce((acc, current) => {
const x = acc.find(item => item.game.id === current.game.id);
if (!x) {
current.platform = [current.platform.name]
return acc.concat([current]);
} else {
x.platform.push(current.platform.name);
return acc;
}
}, []);
console.log(filteredArr);
Here is another solution, using forEach instead of reduce. This makes use of a lookup hash that makes if faster for larger amounts of data then using find.
const data = [{"id": 157283, "date": 1553212800, "game": {"id": 76882, "name": "Sekiro: Shadows Die Twice", "popularity": 41.39190295640344}, "human": "2019-Mar-22", "m": 3, "platform": {"id": 48, "name": "PlayStation 4"}, "region": 8, "y": 2019}, {"id": 12, "date": 1553212800, "game": {"id": 76832, "name": "Spiderman", "popularity": 41.39190295640344}, "human": "2019-Mar-22", "m": 3, "platform": {"id": 6, "name": "PC (Microsoft Windows)"}, "region": 8, "y": 2019}, {"id": 157283, "date": 1553212800, "game": {"id": 76882, "name": "Sekiro: Shadows Die Twice", "popularity": 41.39190295640344}, "human": "2019-Mar-22", "m": 3, "platform": {"id": 48, "name": "Xbox"}, "region": 8, "y": 2019}];
let result = {};
data.forEach(({platform, ...release}) => {
release.platforms = [platform.name];
const releaseLookup = result[release.game.id];
if (!releaseLookup) {
result[release.game.id] = release;
} else {
releaseLookup.platforms.push(...release.platforms);
}
});
console.log(Object.values(result));
I am new in angular 4. While trying to make a search bar got stuck in the logic. So I have a JSON file, and I am trying to search relevant key value pair of that JSON file based on an array values.
My json file :
const trips = {
"20180201": [{
"journeyId": 1001,
"Number": "001",
"DriverName": "Alex",
"Transporter": {
"id": "T1",
"number": "AN01001",
"Company": "Tranzient"
},
"place": [{
"id": 001,
"value": "Washington DC"
},
{
"id": 002,
"value": "Canberra"
}
],
},
{
"journeyId": 1002,
"Number": "001",
"DriverName": "Tom",
"Transporter": {
"id": "T2",
"number": "AN01002",
"Company": "Trax"
},
"place": [{
"id": 2,
"value": "Canberra"
},
{
"id": 4,
"value": "Vienna"
}
],
},
{
"journeyId": 1003,
"Number": "004",
"DriverName": "Jack",
"Transporter": {
"id": "T3",
"number": "AN01003",
"Company": "Trax"
},
"place": [{
"id": 1,
"value": "Washington DC",
}, {
"id": 4,
"value": "Vienna",
}],
}
],
"20180211": [{
"journeyId": 1004,
"Number": "005",
"DriverName": "Jack",
"Transporter": {
"id": "T3",
"number": "AN01013",
"Company": "Trax"
},
"place": [{
"id": 5,
"value": "Bridgetown"
},
{
"id": 6,
"value": "Ottawa"
},
{
"id": 4,
"value": "Boston"
}
],
},
{
"journeyId": 1005,
"Number": "005",
"DriverName": "Jerry",
"Transporter": {
"id": "T3",
"number": "AN01020",
"Company": "Trax"
},
"place": [{
"id": 5,
"value": "Bridgetown"
},
{
"id": 6,
"value": "Ottawa"
}
],
}
],
"20180301": [{
"journeyId": 1006,
"Number": "005",
"DriverName": "demy",
"Transporter": {
"id": "T3",
"number": "AN01003",
"Company": "Trax"
},
"place": [{
"id": 5,
"value": "Bridgetown"
},
{
"id": 6,
"value": "Vienna"
}
],
}],
};
I have an array
SelectedValues= ["20180201","Vienna"]
All the array values should search depending on the result from its previous array value. For example in this array above, I need to return key value pair of all the places which have its value "Vienna" in date "20180201".
expected output:
trips= {
"20180201": [
{
"journeyId": 1002,
"Number": "001",
"DriverName": "Tom",
"Transporter": {
"id": "T2",
"number": "AN01002",
"Company": "Trax"
},
"place": [{
"id": 2,
"value": "Canberra"
},
{
"id": 4,
"value": "Vienna"
}
],
},
{
"journeyId": 1003,
"Number": "004",
"DriverName": "Jack",
"Transporter": {
"id": "T3",
"number": "AN01003",
"Company": "Trax"
},
"place": [{
"id": 1,
"value": "Washington DC",
}, {
"id": 4,
"value": "Vienna",
}],
}
]
}
So the result returns all the key value pair that have place "Vienna" within the date " 20180201 " .
My solution that I tried to use :
filter(trips, SelectedValues) {
const check = v => options.includes(v) || v && typeof v === 'object' && Object.keys(v).some(l => check(v[l]));
var result = {};
Object.keys(object).forEach(function (k) {
var temp = options.includes(k)
? object[k]
: object[k].filter(check);
if (temp.length) {
result[k] = temp;
}
});
return result;
}
The problem is that it is returning all the key-value pairs that matches all the values in SelectedValues(Implementing OR logic). But I need to implement the array search with AND logic.