NGTools/js_sdk/util/jsonData.js
ldeyun 9dbfdc6c71 V1.0.0
微信小程序运行成功;
H5运行成功
2024-09-30 01:30:39 +08:00

48 lines
960 B
JavaScript

export function groupBy(array, key) {
return array.reduce((result, currentItem) => {
// 使用 key 的值作为分组的键
const groupKey = currentItem[key];
// 如果 result 中不存在这个键,则创建一个数组
if (!result[groupKey]) {
result[groupKey] = [];
}
// 将当前项推入对应的分组数组中
result[groupKey].push(currentItem);
return result;
}, {});
}
export function getJsonTree(items) {
const rootItems = [];
const lookup = {};
for (const item of items) {
const itemId = item._id;
const parentId = item.parent_id;
if (!lookup[itemId]) lookup[itemId] = {
['children']: []
};
lookup[itemId] = {
...item,
children: lookup[itemId]['children']
};
const parent = parentId ? lookup[parentId] : null;
if (parent) {
if (!parent.children) parent.children = [];
parent.children.push(lookup[itemId]);
} else {
rootItems.push(lookup[itemId]);
}
}
return rootItems;
}