对象扁平化
Sunny-117 opened this issue · comments
对象扁平化
递归法:
let arr = [1, [2, [3, 4, 5]]];
function flatten(arr){
let result = [];
for(let i = 0; i < arr.length; i++){
if(arr[i] instanceof Array){
result = result.concat(flatten(arr[i]))
} else {
result.push(arr[i])
}
}
return result;
}
flatten(arr);
楼上是数组扁平化
- 递归
function flattenObject(obj, prefix = '', res = {}) {
for (let key in obj) {
let newKey = prefix ? `${prefix}.${key}` : key;
if (typeof obj[key] === 'object' && obj[key] !== null && !(obj[key] instanceof Date)) {
flattenObject(obj[key], newKey, res);
} else {
res[newKey] = obj[key];
}
}
return res;
}
- 堆栈
function flattenObjectStack(obj) {
const stack = [[[], obj]];
const result = {};
while (stack.length > 0) {
const [keys, value] = stack.pop();
if (typeof value === 'object' && value !== null && !(value instanceof Date)) {
for (let k in value) {
stack.push([[...keys, k], value[k]]);
}
} else {
result[keys.join('.')] = value;
}
}
return result;
}
// 对象扁平化
const nestedObject = {
a: 1,
b: {
c: 2,
d: {
e: 3
}
}
};
const flattened = flattenObject(nestedObject);
console.log(flattened);
function flattenObject(obj){
let res = {};
for(let [key, value] of Object.entries(obj)){
if(typeof value === 'object'){
let newObj = flattenObject(value)
Object.keys(newObj).forEach(item => {
let str = `${key}.${item}`;
res[str] = newObj[item];
})
}else{
res[key] = value;
}
}
return res;
}