Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

对象扁平化 #77

Open
Sunny-117 opened this issue Nov 3, 2022 · 3 comments
Open

对象扁平化 #77

Sunny-117 opened this issue Nov 3, 2022 · 3 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@ych-chen
Copy link

递归法:

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);

@kangkang123269
Copy link

楼上是数组扁平化

  1. 递归
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;
}
  1. 堆栈
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;
}

@Lupengcheng7
Copy link

// 对象扁平化
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;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants