찾다

 >  Q&A  >  본문

javascript - Object 提取值

const from = {
    a: {
        b: ['01', '02']
    },
    c: {
        d: {
            e: ['03', '04']
        },
        f: ['05', '06']
    }
}
=>
to1 = {
    a: {
        b: '01'
    },
    c: {
        d: {
            e: '03'
        },
        f: '05'
    }
}
to2 = {
    a: {
        b: '02'
    },
    c: {
        d: {
            e: '04'
        },
        f: '06'
    }
}

这边拿到的是一个嵌套层级不规则的对象,需要的值是一个数组,数组的长度是固定的,现在想要做的是通过数组的长度来拆分这个对象,把这个对象拆分成和数组长度一样个数的对象,嵌套格式和key不变,对应提取数组的第n个值,有没有什么好的办法?

PHPzPHPz2894일 전239

모든 응답(3)나는 대답할 것이다

  • 伊谢尔伦

    伊谢尔伦2017-04-10 17:54:25

    一次遍历的实现,感觉还有更优雅的实现

    const from = {
      a: {
        b: ['01', '02']
      },
      c: {
        d: {
          e: ['03', '04']
        },
        f: ['05', '06']
      }
    }
    
    console.log(splitByIndex(from));
    
    function splitByIndex(obj) {
      let res = [];
      run([], obj);
    
      return res;
    
      function run(pre, obj) {
        let item;
        for (let i in obj) {
          item = obj[i];
          let currentPre = Array.prototype.concat(pre, i);
          if (Array.isArray(item)) return addObj(currentPre, item);
          run(currentPre, item);
        }
      }
    
      function addObj(pre, item) {
        item.forEach((v, i) => {
          if (!res[i]) res[i] = {};
          let tmp = res[i];
          let max = pre.length - 1;
          let prefix;
          for (let j = 0; j < max; j++) {
            prefix = pre[j];
            if (!tmp[prefix]) tmp[prefix] = {};
            tmp = tmp[prefix];
          }
          tmp[pre[max]] = [v];
        });
      }
    }

    회신하다
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-10 17:54:25

    递归。用对象表示。

    회신하다
    0
  • 迷茫

    迷茫2017-04-10 17:54:25

    一个简单的递归方法,for...in性能好。

    const to1 = tran (from, 0)
    const to2 = tran (from, 1)
    
    function tran (obj, propKey) {
      let newObj = {}
      for (let key in obj) {
        const value = obj[key]
        if (Array.isArray(value)) {
          newObj[key] = value[propKey]
        } else {
          newObj[key] = cutLang(value, propKey)
        }
      }
      return newObj
    }

    회신하다
    0
  • 취소회신하다