【发布时间】:2022-01-13 02:42:34
【问题描述】:
从服务器返回的数据包含一个字符串数组,其层次结构如下:
var array = [
"house.bedroom.bed",
"house.kitchen.spoon",
"house.kitchen.knife",
"house.bedroom.sofa",
"house.bedroom.tv",
"plants.trees",
"house.birds.parrot.grey"
]
我已经成功地制作了一个树形数据结构作为对象,以便以下面的树形输出数据:
house
bedroom
bed
sofa
tv
kitchen
spoon
knife
birds
parrot
grey
plants
trees
有没有办法选择一个字符串?例如,询问“厨房”我想像这样返回与该字符串相关的所有内容:
house.kitchen.knife
house.kitchen.spoon
这里是我学到的代码:
function find([key, values], string, temp = []) {
var result;
temp = temp.concat(key);
if (key === string) {
return temp.slice(1).join('.');
}
values.some(a => result = find(a, string, temp));
return result;
}
var result = array.reduce((r, s) => {
('root.' + s).split('.').reduce((a, item) => {
var array = a.find(([v]) => v === item);
if (!array) {
a.push(array = [item, []]);
}
return array[1];
}, r);
return r;
}, []).pop();
console.log(find(result, 'kitchen'));
console.log(result);
我的输出是:
house.kitchen
【问题讨论】:
-
我想你只需要过滤源数组
array.filter((path) => path.split('.').includes('kitchen')) -
我试过它工作得很好,但目标是我需要将 array = [] 输出转换为对象以满足树数据结构,然后我应用 find() 函数来查找匹配的父级和子级相关的“厨房”........我制作了树,但无法运行 find() 来匹配“厨房”的父级和子级以满足预期输出
-
你有一个从数组中生成树的函数。只需从过滤后的数组中制作树即可。
标签: javascript arrays data-structures tree hierarchy