export const serialize = (data, sections = [], weeks = []) => {
const getWithParentArray = (newArr, parentIndex = -1, parentIndexObj = {}) =>
newArr.map((item, index) => {
if (item.node_lev < 2) {
let parentObj = {};
if (parentIndex > -1) {
weeks[parentIndex].push(item.title);
parentObj = { section: parentIndex, week: index };
} else if (item.node_lev === 0) {
sections.push(item.title);
weeks.push([]);
}
return getWithParentArray(item.children, index, parentObj);
}
return { ...item, week: parentIndex, ...parentIndexObj };
});
return {
sections,
weeks,
courses: getWithParentArray(data),
};
};
export const flatten = (data, arr = []) => {
data.forEach((item) => {
if (item instanceof Array) {
flatten(item, arr);
} else {
arr.push(item);
}
});
return arr;
};
/* {
"sections": [
"string"
],
"weeks": [
["string"]
],
"courses": [{
"_id": "string",
"title": "string",
"course_type": "NORMAL",
"section": 0,
"week": 0,
}]
} */
转载于:https://www.cnblogs.com/zhouyideboke/p/9070647.html