想象一下,我有一个项目,它有一个项目数组,并且该数组中的任何项目都有一个项目数组,依此类推。 所以我有无限级别的 Items,我想知道如何在 Node.js 中访问所有这些 Items。 像这样:
Item1
/ \
Item2 Item3
/ \
Item4 Item5
Item1 是一个数组。 Item2 和 Item3 另一个数组等等。
最佳答案
I have an Item that has an array of Items ... i want to know how to get to all of them
如果数组是数组,则递归地展平数组中的每个元素,否则追加它。
/* setup test input */
const tree = [
"leaf_A_1",
"leaf_A_2",
[
"leaf_B_1",
"leaf_B_2",
[
"leaf_C_1",
"leaf_C_2",
]
]
]
console.log("INPUT:\n", tree)
/* run test */
const leaves = flatten(tree)
console.log("OUTPUT:", leaves) // outputs leaf nodes in a flat array
// flatten() is a recursive function takes an array that *may* contain nested arrays, and returns an array containing all leaf elements without nesting.
function flatten(arr) {
return arr.reduce(expandNestedArraysOrAppend, [])
}
function expandNestedArraysOrAppend(accum, element, idx) {
if (Array.isArray(element)) {
return [...accum, ...flatten(element)] // if we have an array, flatten it before appending
}
return [...accum, element] // if not an array, just append
}
希望这有帮助。干杯!
关于arrays - 搜索包含项目数组的项目等node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53133664/