fenzhi-utils
Version:
分值前端项目的js函数库
89 lines (84 loc) • 1.91 kB
JavaScript
/**
* 平铺数组
* @param {array} arr 要平铺的数组
* @param {string} childProp 平铺的子集字段
* @param {boolean} keepChildren 是否删除子集(默认删除)
* @returns {array} 返回平铺后的数组
*/
/*
let arr = [
{
id: 1,
children: [
{
id: 2,
children: [
{
id: 4,
children: [{ id: 8 }, { id: 9 }],
},
{
id: 5,
children: [{ id: 10 }, { id: 11 }],
},
],
},
{
id: 3,
children: [
{
id: 6,
children: [{ id: 12 }, { id: 13 }],
},
{
id: 7,
children: [{ id: 14 }, { id: 15 }],
},
],
},
],
},
{
id: 101,
},
];
CustomArrayFlatter(arr)
CustomArrayFlatter(arr, 'children')
CustomArrayFlatter(arr, 'children', true)
*/
export function CustomArrayFlatter(
arr = [],
childrenKey = 'children',
keepChildren = false
) {
let a = [];
let result = [];
let newArr = JSON.parse(JSON.stringify(arr));
newArr.forEach((item) => {
let children = item[childrenKey];
if (!keepChildren) {
delete item[childrenKey];
}
result.push(item);
if (Array.isArray(children)) {
result = result.concat(
CustomArrayFlatter(children, childrenKey, keepChildren)
);
}
});
return result;
}
// 下面的方法可替换JSON.parse(JSON.stringify(arr))
// function deepCopy(source) {
// if (typeof source != 'object') {
// return source;
// }
// if (source == null) {
// return source;
// }
// var newObj = source.constructor === Array ? [] : {}; //开辟一块新的内存空间
// for (var i in source) {
// newObj[i] = deepCopy(source[i]);
// }
// return newObj;
// }