从Javascript中的递归函数返回一个对象数组



我正在研究递归函数。

我必须推送数组中所有具有关键字"data:true"的对象。位于函数中间的console.log在单独的数组中为我提供了所有这些对象。

但我不能返回一个末尾有对象的数组。我做错了什么?感谢

const entries = {
root: {
data: true,
key: "root",
text: "some text"
},
test: {
one: {
two: {
data: true,
key: "test.one.two",
text: "some text.again"
},
three: {
data: true,
key: "test.one.three",
text: "some.more.text"
}
},
other: {
data: true,
key: "test3",
text: "sometext.text"
}
},
a: {
b: {
data: true,
key: "a.b",
text: "a.b.text"
},
c: {
d: {
data: true,
key: "a.c.d",
text: "some.a.c.d"
}
}
}
};
function recursiveFunc(data) {
let tab = [];
for (let property in data) {
if (data.hasOwnProperty(property)) {
if (data[property].data === true) {
tab.push(data[property]);
console.log("t", tab);
} else {
recursiveFunc(data[property])
}
}
}
return tab
}
console.log(recursiveFunc(entries));

在递归调用上添加tab.concat(),以联接递归fn返回的项。

const entries = {
root: {
data: true,
key: "root",
text: "some text"
},
test: {
one: {
two: {
data: true,
key: "test.one.two",
text: "some text.again"
},
three: {
data: true,
key: "test.one.three",
text: "some.more.text"
}
},
other: {
data: true,
key: "test3",
text: "sometext.text"
}
},
a: {
b: {
data: true,
key: "a.b",
text: "a.b.text"
},
c: {
d: {
data: true,
key: "a.c.d",
text: "some.a.c.d"
}
}
}
};
function recursiveFunc(data) {
let tab = [];
for (let property in data) {
if (data.hasOwnProperty(property)) {
if (data[property].data === true) {
tab.push(data[property]);
console.log("t", tab);
} else { 
tab = tab.concat(recursiveFunc(data[property]));
}
} 
} 
return tab
}
console.log(recursiveFunc(entries));

您可以将数组作为第二个参数传递,该参数将充当累加器。

另外,我修复了当data = false:时无限循环的函数

function recursiveFunc(data, acc) {
for (let property in data) {
if (data.hasOwnProperty(property) && typeof data[property] === "object") {
var current = data[property];
if (current.data === true) {
acc.push(current);
} else {
recursiveFunc(current, acc)
}
}
}
}

用法:

var results = [];
recursiveFunc(entries, results);
console.log(results);

您可以使用全局变量。

const entries = { ... };

var tab = [];
function getTab(data) {
tab = [];
recursiveFunc(data);
return tab;
}
function recursiveFunc(data) {
for (let property in data) {
if (data.hasOwnProperty(property) && typeof data[property] === "object") {
if (data[property].data === true) {
tab.push(data[property]);
} else {
recursiveFunc(data[property])
}
}
}
}
getTab(entries);

最新更新