let data = {
abc: [{x: 13, xx: 'x', hidden: false}, {x: 47, xx: 'y', hidden: true}, {x: 36, xx: 'z', hidden: false}],
def: [{x: 68, xx: 'z', hidden: false}, {x: 91, xx: 'x', hidden: false}, {x: 3, xx: 'y', hidden: true}],
ghi: [{x: 22, xx: 'v', hidden: false}, {x: 1, xx: 'z', hidden: true}, {x: 76, xx: 'w', hidden: false}],
jkl: [{x: 99, xx: 's', hidden: true}, {x: 7, xx: 'm', hidden: false}, {x: 66, xx: 'x', hidden: false}]
};
/*
Pass the data Object, the property to search for, and
one or more values to match
*/
const keepKV = (object, prop, ...values) => {
/*
Convert data Object into an Array of array pairs
ex.
let data = {'abc': [{...}, {...}, {...}], 'def': [...]}
to
data = [['abc',[{...}, {...}, {...}]], ['def', [...]]
Object.entries(object)...
*/
/*
Destructure the .map() parameter
ex.
subKey = 'abc'
subArray = [{...}, {...}, {...}]
.map(([subKey, subArray]) => {...
*/
/*
The last return on each iteration is an array of pairs:
[subKey, [subArray]]
ex.
["jkl", [{...}, {...}, {...}]]
Each object of each subArray gets .filter()
return [subKey, subArray.filter(subObject => [...values].includes(subObject[prop]))];
*/
/*
The entire returned Array of arrays is then converted
back into an Object
Object.fromEntries(ArrayOfArrays)
*/
return Object.fromEntries(Object.entries(object).map(([subKey, subArray]) => {
return [subKey, subArray.filter(subObject => [...values].includes(subObject[prop]))];
}));
};
// Utility function that creates a ranged Number array
let range = Array(...Array(26)).map((_, i) => 5+i);
// Get all objects that has x: 5 to 30
const range5to30 = keepKV(data, 'x', ...range); console.log(`Key: 'x', Values: range\n
const range5to30 = ${JSON.stringify(range5to30, null, 2)}\n`);
// Get all objects that has xx: 'z' and/or 'x'
const xZOnly = keepKV(data, 'xx', 'z', 'x');
console.log(`Key: 'xx', Values: 'z', 'x'\n
const xZOnly = ${JSON.stringify(xZOnly, null, 2)}\n`);
// Get all objects that has hidden: false
const notHidden = keepKV(data, 'hidden', false);
console.log(`Key: 'hidden', Values: false\n
const notHidden = ${JSON.stringify(notHidden, null, 2)}\n`);
.as-console-wrapper {
width: 375px;
min-height: 100%;
margin-left: 25%;
}
.as-console-row {
border-bottom: 5px ridge #333
}
.as-console-row-code::first-line {
text-decoration: underline;
}
.as-console-row.as-console-row::after,
.as-console-row-code.as-console-row-code::after {
content:'';
padding:0;
margin:0;
border:0;
width:0;
}