Sunny-117/js-challenges

逆对象扁平

Sunny-117 opened this issue · 3 comments

逆对象扁平

简单实现

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] } }
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] } }
let testObj = { 
    'a.b.c': 1,
    'd.e.f': [2,3],
    'd.e.g':3,
   };
   
console.log(unflattenObject1(testObj)); // 输出:{ a: { b: { c: 1 } }, d: { e: { f: [Array], g: 3 } } }

// 逆对象扁平化
function unflattenObject(obj){
    let result = {}
    for(let [key, value] of Object.entries(obj)){
        let keys = key.split('.');
        result[keys[0]] = result[keys[0]] || {};
        let newObj = result[keys[0]];
        for(let i = 1; i < keys.length; i++){
            if(i === keys.length - 1){
                newObj[keys[i]] = value
            }else{
                newObj[keys[i]] = newObj[keys[i]] || {}
                newObj = newObj[keys[i]]
            } 
        }
    }

    return result
}

function unflattenObject1(obj){
    let res = {};
    for(let [key, value] of Object.entries(obj)){
        let keys = key.split('.');
        keys.reduce((acc, cur, index) => {
            if(index === keys.length - 1){
                acc[cur] = value;
            }else{
                acc[cur] = acc[cur] || {};
            }
            return acc[cur];
        }, res)
    }
    return res;
}