js数组扁平化
// 原始数据
let arr = [1,2,[3,4,[5,6,[7,8,[9,10],11],12],13],14,[15,[16,[17,18]]]];
代码如下:
let dofn = (arr) =>{
let result = [];
let tempArr = (params) =>{
params.forEach(element => {
if(Array.isArray(element)){
// 递归: 函数自己调用自己。
tempArr(element);
}else{
result.push(element);
}
});
}
tempArr(arr);
return result;
}
console.log('新数组--', dofn(arr));
// 打印结果: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
json数据扁平化
// 原始数据
let obj = {
id: 1,
age: 11,
children: [
{
id: 2,
age: 22,
children: [
{
id: 7,
age: 77,
children: [],
}
]
},
{
id: 3,
age: 33,
children: [
{
id: 4,
age: 44,
},
{
id: 5,
age: 55,
children: [
{
id: 6,
age: 66,
children: []
}
]
}
]
},
{
id: 8,
age: 88,
children: [
{
id: 9,
age: 99,
children: [],
}
]
},
{
id: 10,
age: 100,
children: [],
}
]
}
代码如下:
let objFn = (params) =>{
let arr = [];
arr.push(params);
let result = [];
let changeFn = (a, parentId = null) =>{
a.forEach((item)=>{
//ES6:解构运算符...为剩余运算符,是扩展运算符的一种用法。
let { children, ...i } = item;
result.push({
...i,
parentId,
});
if(children && children.length){
// 递归。 传入父id
changeFn(children, item.id);
}
})
}
changeFn(arr);
return result;
}
console.log('json--', objFn(obj));