一、使用递归实现数组的扁平化
let arr = [
[1,1,1,2],
[2,3,[4,4]],
[3,5,[7,9,[20,88,[0]]]]
]
let result = []
function arrFlat(array){
array.forEach(element => {
if (Array.isArray(element)) {
arrFlat(element)
} else {
result.push(element)
}
});
return result
}
console.log([...new Set(arrFlat(arr).sort((a,b)=>a-b))]);
//[0, 1, 2, 3, 4, 5, 7, 9, 20, 88]
二、使用递归实现对象的扁平化
let obj = {
a: {
b: {
c: {
dd: "abcd",
},
},
d: {
xx: "js",
},
e: "aa",
},
};
function objectFlat(object, prefix = "") {
let result = {};
for (const key in object) {
if (object.hasOwnProperty(key)) {
if (typeof object[key] === "object") {
result = { ...result, ...objectFlat(object[key], prefix + key + ".") };
} else {
result[prefix + key] = object[key];
}
}
}
return result;
}
console.log(objectFlat(obj));
//{a.b.c.dd: 'abcd', a.d.xx: 'js', a.e: 'aa'}