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
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));
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.