javascript - 将包含数组作为值的对象减少为单个数组
问题描述
问题:根据条件将包含数组作为值的对象减少为单个数组。详细信息:我有一个包含数组作为值的对象。
{
514:["564"],
812:["514"],
1006:["921","812"],
1012: ["1002"],
1024:["6994","7992"],
6923:["1024","1006"],
6994:["1012","7182"],
7992:["5921"],
}
我想编写一个javascript函数,可以根据我传递给函数的键将此对象简化为数组。结果数组应该有我们传递给函数的 id 和它在对象中的值以及与这些值相对应的任何其他值,直到我们找不到键为止。例如:如果我通过 6994,那么我需要函数的结果为以下数组
["6994", "1012", "7182", "1002"]
我尝试了以下工作。想知道是否有更好更有效的解决方案:
function getChildIds({ treeMap, id }) {
let childIds = [id];
let parentIds = [id];
while(!!parentIds.length) {
let tempIds = [];
parentIds.forEach((parentId, index) => {
if(!!treeMap[parentId]) {
tempIds.push(...treeMap[parentId]);
childIds.push(...treeMap[parentId]);
}
});
parentIds = tempIds;
}
return childIds;
}
编辑:递归不是首选,因为这个对象可能非常大,并且浏览器堆栈内存不足是不可取的。
解决方案
您可以从给定节点获取嵌套节点。
类型:深度优先搜索:有序(LNR)
const
getNodes = node => [node, ...(nodes[node] || []).flatMap(getNodes)],
nodes = { 514: ["564"], 812: ["514"], 1006: ["921", "812"], 1012: ["1002"], 1024: ["6994", "7992"], 6923: ["1024", "1006"], 6994: ["1012", "7182"], 7992: ["5921"] },
node = "6994",
result = getNodes(node);
console.log(result);
另一种方法使用堆栈,它可能比上述递归reduce
方法更快。
这种方法的顺序是不同的,因为树遍历是按级别顺序(广度优先搜索)。
const
getNodes = node => {
const
stack = [node],
result = [];
while (stack.length) {
const
n = stack.shift();
result.push(n);
if (!nodes[n]) continue;
stack.push(...nodes[n]);
}
return result;
},
nodes = { 514: ["564"], 812: ["514"], 1006: ["921", "812"], 1012: ["1002"], 1024: ["6994", "7992"], 6923: ["1024", "1006"], 6994: ["1012", "7182"], 7992: ["5921"] },
node = "6994",
result = getNodes(node);
console.log(result);
推荐阅读
- python - ImportError:无法导入名称请求
- python - NiftyNet ValueError:维度 -1 必须 >= 0
- python - 如何在 TensorFlow 中的这个神经网络中实现剩余的“for循环”
- android - 在画布上绘图时屏蔽圆形/形状
- css - Django CSS 相对路径在 Amazon S3 中不起作用
- django - djangocms:将数据从已弃用的 cmsplugin-filer-*-plugins 移动到 djangocms-*-plugins
- java - 如何在 JMETER 中将环境属性 json 文件读取到 UDV
- hive - Hive 插入权限被拒绝:user=root,access=WRITE
- validation - Magento 2如何在keyup事件上验证客户注册表单
- python - SQL比较两个选择子句和分组总和