I have a dictionary called teamData
var teamData = {
app: {
sortCol:"name",
sortDir:"asc"
},
data: [
{
id: 1,
name:"Raptors",
coachId: 1,
coachFirst: "Ken",
coachLast: "jenson",
coachPhone: "801-333-4444",
coachEmail: "[email protected]",
coachLicenseLevel: 1,
league: 1,
division: 1
},
{
id: 2,
name:"Killer Bunnies",
coachId: 2,
coachFirst: "Peter",
coachLast: "Rabbit",
coachPhone: "801-333-4444",
coachEmail: "[email protected]",
coachLicenseLevel: 1,
league: 1,
division: 2
},
{
id: 3,
name:"Thunderbirds",
coachId: 3,
coachFirst: "Harry",
coachLast: "DirtyDog",
coachPhone: "801-333-4444",
coachEmail: "[email protected]",
coachLicenseLevel: 2,
league: 1,
division: 2
}
]
}
I'm trying to write a function that takes a key/value object and returns a filtered dictionary. So if the function is
let teams = filter({coachLicenseLevel:1});
then the expected result is to return a filtered dictionary with only two elements that have that key/value pair
Here is the function I have so far, but I'm stuck on how to get the key object.
filter(filterObj) {
const v = Object.values(filterObj);
const k = Object.keys(filterObj);
const res = teamData.filter(({???}) => v.includes(???));
}
any help would be appreciated.
CodePudding user response:
If you want to filter only the data array, you could do something like this:
function filterArrayByParamAndValue(arr, itemParam, value) {
return arr.filter(item => item.itemParam === value)
}
And in your code just replace the data
property, if
let teamData = {
....,
data: [...filterArrayByParamAndValue(teamData.data, coachLicenseLevel, 1)],
....
}
Of course you should also add all necessary checks in the filter function, or even add an object property to check for and pass the whole object.
CodePudding user response:
Instead of passing an object, you may consider using the filter function with your custom filter logic. Here is an example for your specific case:
let teams = teamData.data.filter(item => item.coachLicenseLevel == 1)