我编写了一个函数来搜索嵌套对象。问题在于它返回了labels
而不是预期的结果,该结果已正确记录在控制台中。那里发生了什么事?
undefined
答案 0 :(得分:2)
只需在末尾添加return
。
return keys.map(key =>
findVDOMNode(instance, vDOM[key].children));
您可以获取对象的值并对照实例进行检查。如果找到了对象,请同时检查该对象。如果发现该实例,请使用some
进行短路迭代。
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));
答案 1 :(得分:0)
您似乎在函数的最后一行中缺少地图上的return语句
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));