Reputation: 503
I have written a function to search in a nested object. The problem is that it returns undefined
instead of the expected result, that is correctly logged in the console. Whats going on there?
const in1 = [1, 2];
const in2 = [1, 2];
const vDOM = {
1: {
ref: in1,
children: {
2: {
ref: in2,
children: {}
}
}
}
}
const findVDOMNode = function(instance, vDOM) {
const keys = Object.keys(vDOM);
const foundKey = keys.find(key => vDOM[key].ref === instance);
//console.log(foundKey, vDOM, "FK");
if (!keys.length) {
console.log('no keys');
return;
}
if (foundKey) {
console.log('found', vDOM[foundKey]);
return true; //vDOM[foundKey];
};
keys.map(key =>
findVDOMNode(instance, vDOM[key].children));
}
console.log('res: ', findVDOMNode(in2, vDOM));
Live example: https://stackblitz.com/edit/js-dapzsy
Upvotes: 1
Views: 103
Reputation: 386519
Just add return
at the end.
return keys.map(key =>
findVDOMNode(instance, vDOM[key].children));
You could take the values of the object and check it against the instance. If an object is found, check the object as well. For iterating use some
with short circuit, if the instance is found.
const
in1 = [1, 2],
in2 = [1, 2],
vDOM = { 1: { ref: in1, children: { 2: { ref: in2, children: {} } } } },
findVDOMNode = (instance, vDOM) => Object
.values(vDOM)
.some(v => v === instance
|| v && typeof v === 'object' && findVDOMNode(instance, v)
);
console.log('res: ', findVDOMNode(in2, vDOM));
Upvotes: 2
Reputation: 196
it looks like you are missing a return statement on the map in the last line of the function
const in1 = [1, 2];
const in2 = [1, 2];
const vDOM = {
1: {
ref: in1,
children: {
2: {
ref: in2,
children: {}
}
}
}
}
const findVDOMNode = function(instance, vDOM) {
const keys = Object.keys(vDOM);
const foundKey = keys.find(key => vDOM[key].ref === instance);
//console.log(foundKey, vDOM, "FK");
if (!keys.length) {
console.log('no keys');
return;
}
if (foundKey) {
console.log('found', vDOM[foundKey]);
return true; //vDOM[foundKey];
};
///added this return statement
return keys.map(key =>
findVDOMNode(instance, vDOM[key].children));
}
console.log('res: ', findVDOMNode(in2, vDOM));
Upvotes: 0