I have received an object and an array. My task is to filter the object so that it only contains nodes where either the key or the value matches with the keys provided in the array. For example:
Array containing keys -
['student1', 'STU', 'LMN', 'student4']
INPUT
{
student1: {
name: 'ABC',
roll: 17,
},
student2: {
name: 'LMN',
roll: 16
},
student3: {
name: 'MNO',
roll: 15
},
student4: {
name: 'PQR',
roll: 16
}
}
OUTPUT
{
student1: {
name: 'ABC',
roll: 17,
},
student2: {
name: 'LMN',
roll: 16
},
student4: {
name: 'PQR',
roll: 16
}
}
INPUT
{
student1: {
name: 'ABC',
roll: 17,
friends: {
student5: {},
student6: {}
}
},
student2: {
name: 'LMN',
roll: 16
},
student3: {
name: 'MNO',
roll: 15,
friends: {
student7: {
name: 'STU'
}
}
},
student4: {
name: 'PQR',
roll: 16
}
}
OUTPUT:
{
student1: {
name: 'ABC',
roll: 17,
friends: {
student5: {},
student6: {}
}
},
student2: {
name: 'LMN',
roll: 16
},
student3: {
name: 'MNO',
roll: 15,
friends: {
student7: {
name: 'STU'
}
}
},
student4: {
name: 'PQR',
roll: 16
}
}
INPUT
{
student5: {
name: 'EFG',
roll: 10,
friends: {
student1: {},
student2: {}
}
}
}
OUTPUT:
{
student5: {
name: 'EFG',
roll: 10,
friends: {
student1: {}
}
}
}
Explanation :
The keys given are
'student1', 'student4', 'STU' and 'LMN'
. Therefore, we search through the entire object and include entries where either the key or the value matches those provided keys. If a key in the object matches the keys from the array, we do not need to check its contents.
For example, if 'student1' is in the keys array, we include it without checking its content.
NOTE: The object can be deeply nested as well.
MY APPROACH
I attempted to parse the object and filter out entries based on their presence, but I am not getting the correct results,
const containsKey = (obj, arr = []) => {
return (
obj &&
typeof obj === "object" &&
(arr.some((key) => key in obj) ||
arr.indexOf(obj[targetKey]) > -1 ||
Object.values(obj).filter((obj) => {
return containsKey(obj, arr);
}))
);
};
Object.fromEntries(
Object.entries(obj).filter(([k, v]) =>
containsKey({ [k]: v }, arr)
)
);
Any assistance would be greatly appreciated. Thank you :)