【发布时间】:2020-08-03 18:48:22
【问题描述】:
我想根据嵌套子项的值显示结果。我为此使用递归函数。根据下面的示例结果,我无法将其显示为 HTML。 我正在使用 React.js。
现在我正在使用 console.log。 这是我的代码:(示例数据在底部)
function recursion(data, label) {
if (!data) {
return;
}
for (let a = 0; a < data.length; a++) {
const item = data[a]
if (!item.items) {
const isLast = data.length - a === a
console.log(`(${item.course_id}) ${ isLast ? '' : label} `)
} else {
if (label) console.log(label)
recursion(item.items, item.type)
}
}
}
/*
Example result that I want to achieve is something like be:
(1894 $or 1501)
$or
(7068 $or 7120 or 7141)
$or
(997 $and 9001)
$or
(7256 $or 4534)
*/
//My sample data:
const data = [{
"type": "$or",
"items": [{
"course_id": "1894"
},
{
"course_id": "1501"
},
{
"type": "$or",
"items": [{
"course_id": "7068"
},
{
"course_id": "7120"
},
{
"course_id": "7141"
},
{
"type": "$and",
"items": [{
"course_id": "997"
},
{
"course_id": "9001"
}
]
}
]
},
{
"type": "$or",
"items": [{
"course_id": "7256"
},
{
"course_id": "4534"
}
]
}
]
}]
//start here
recursion(data)
【问题讨论】:
-
按console.log显示?
-
不,我想在 HTML 中将其显示为文本。我只是使用 console.log 进行调试。
-
997前面应该有缩进还是故意的?
-
不需要缩进。我会编辑它。
-
我更新了我的代码,我几乎得到了它,但现在,我在 console.log 中显示它,我的结果中仍然存在一个小问题。 @科林
标签: javascript html css reactjs ecmascript-6