I need to go through the json object and find keys-objects, keys-arrays whose size matches a given value.
I can’t understand where to set the conditions.
function traverse(obj, size) {
for (let key in obj) {
if (typeof obj[key] === "object" && obj[key] != null) {
traverse(obj[key]);
if (Object.keys(obj[key]).length > size) {
console.log(key);
} else if (Array.isArray(obj[key])) {
if (obj[key].length > size) {
console.log(key);
}
}
}
}
}
I’ve tried rearranging the if conditions, but it doesn’t give any good results
3
Answers
You are calling traverse with only one argument.
it should be
Please privide object example with desired result to verify the logic
else if (Array.isArray(obj[key])) {
where you handle an object (not an array):I’ve corrected some parts of your function as per my understanding. This should work. If it doesn’t, let me know in the comments what error/bug you encounter. Preferably, add an instance/simplified example of the object you’re traversing to your question.
EDIT: Here’s the final draft of a tested solution: