数据扁平化的算法

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,
}]
} */
posted @ 2018-05-22 10:11  又回到了起点  阅读(511)  评论(0编辑  收藏  举报