业务需要把children里面的对象取出来放到外面。
第一种方法:
function flattenObject(obj) {
let result = {};
for (let key in obj) {
// 根据业务需求,展开某个字段
if (key === 'children') {
continue;
}
if (typeof obj[key] === 'object' && obj[key] !== null) {
let flattenedChild = flattenObject(obj[key]);
result = { ...result, ...flattenedChild };
} else {
result[key] = obj[key];
}
}
if (obj.children && obj.children.length > 0) {
for (let child of obj.children) {
let flattenedChild = flattenObject(child);
result = { ...result, ...flattenedChild };
}
}
return result;
}
let obj = [
{ a: 1, b: 1, children: [{ c: 1 }] },
{ a: 1, b: 1, children: [{ c: 1, d:1 }]
}];
let result = obj.map((item) => flattenObject(item));
console.log(result);
第二种方法:
/**
* 摊开数组里面的子级元素,全部排列成一层
* @param {*} data
* @returns
*/
export function flattenChildren(data) {
const result = [];
for (let i = 0; i < data.length; i++) {
const item = data[i];
result.push(item);
if (item.child && item.child.length > 0) {
const children = flattenChildren(item.child);
result.push(...children);
delete item.child;
}
}
return result;
}
输出结果:
将嵌套数组展平成一维数组:
const data = [1, [2, [3]]];
const flattened = data.flat(Infinity);
console.log(flattened);