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

逆对象扁平 #78

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

逆对象扁平 #78

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

Comments

@Sunny-117
Copy link
Owner

No description provided.

@kangkang123269
Copy link

简单实现

function unflattenObject(data) {
  let result = {};

  for (let key in data) {
    let keys = key.split('.');
    keys.reduce((r, k, i, a) => {
      return r[k] || (r[k] = isNaN(a[i + 1]) ? (a.length - 1 === i ? data[key] : {}) : []);
    }, result);
  }

  return result;
}

let testObj = { 
 'a.b.c': 1,
 'd.e': [2,3],
};

console.log(unflattenObject(testObj)); // 输出:{ a: { b: { c: 1 } }, d: { e: [2,3] } }

@Liu6625
Copy link

Liu6625 commented Oct 17, 2023

function unflattenObject(data) {
  let obj = {}
  for (const key in data) {
    let keys = key.split('.');
    let tmp = obj;
    for (let i = 0; i < keys.length; i++) {
      if (i === keys.length - 1){
        tmp[keys[i]] = data[key];
        break;
      }
      if (!Object.hasOwnProperty.call(tmp, keys[i])) {
        tmp[keys[i]] = {};
      }
      tmp = tmp[keys[i]];
    }
  }

  return obj
}

let testObj = { 
  'a.b.c': 1,
  'd.e': [2,3],
 };
 
 console.log(unflattenObject(testObj)); // 输出:{ a: { b: { c: 1 } }, d: { e: [2,3] } }

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

3 participants