【问题标题】:flattening the nested object in javascript在javascript中展平嵌套对象
【发布时间】:2019-07-20 16:05:41
【问题描述】:

我遇到了这个问题,我能够编写可以处理对象数组(未在此处发布)或一级深度嵌套对象的解决方案,但是当给定对象具有如下嵌套结构时我无法解决。我很想知道我们如何解决这个问题。

const source = {
  a: 1,
  b: {
    c: true,
    d: {
      e: 'foo'
    }
  },
  f: false,
  g: ['red', 'green', 'blue'],
  h: [{
    i: 2,
    j: 3
  }]
};

解决方案应该是

const solution = {
    'a': 1,
    'b.c': true,
    'b.d.e': 'foo',
    'f': false,
    'g.0': 'red',
    'g.1': 'green',
    'g.2': 'blue',
    'h.0.i': 2,
    'h.0.j': 3
};

尝试一个深层嵌套对象

let returnObj = {}

let nestetdObject = (source, parentKey) => {

    let keys = keyFunction(source);

    keys.forEach((key) => {
      let values = source[key];

      if( typeof values === 'object' && values !== null ) {
        parentKey = keys[0]+'.'+keyFunction(values)[0]
        nestetdObject(values, parentKey);
      }else{
        let key = parentKey.length > 0 ? parentKey : keys[0];
        returnObj[key] = values;
      }
    })
    return returnObj
};

// Key Extractor 
let keyFunction = (obj) =>{
  return Object.keys(obj);
}

调用函数

nestetdObject(source, '')

但是如果对象像{ foo: { boo : { doo : 1 } } },我的尝试将失败。

【问题讨论】:

    标签: javascript arrays typescript data-structures javascript-objects


    【解决方案1】:

    我参加聚会的时间很晚,但可以通过 Flatify-obj 之类的模块轻松实现。

    用法:

       const flattenObject = require('flatify-obj');
    
       flattenObject({foo: {bar: {unicorn: '?'}}})
       //=> { 'foo.bar.unicorn': '?' }
    
       flattenObject({foo: {unicorn: '?'}, bar: 'unicorn'}, {onlyLeaves: true});
       //=> {unicorn: '?', bar: 'unicorn'}
    

    【讨论】:

      【解决方案2】:

      Object.keys 的另一个简单示例

       const apple = { foo: { boo : { doo : 1 } } }
      
      
      let newObj = {}
      const format = (obj,str) => {
        Object.keys(obj).forEach((item)=>{
           if(typeof obj[item] ==='object'){
              const s = !!str? str+'.'+item:item
              format(obj[item],s)
           } else {
             const m = !!str?`${str}.`:''
             newObj[m+item]= obj[item]
           }
        })
      
      }
      
      format(apple,'')
      
      console.log(newObj)

      【讨论】:

        【解决方案3】:

        您应该能够通过递归相当简单地做到这一点。它的工作方式是,您只是递归地调用对象子对象的解析器,该对象子对象沿途添加正确的键。例如(虽然没有经过非常严格的测试):

        const source = {
          a: 1,
          b: {
            c: true,
            d: {
              e: 'foo'
            }
          },
          f: false,
          g: ['red', 'green', 'blue'],
          h: [{
            i: 2,
            j: 3
          }]
        }
        
        const flatten = (obj, prefix = '', res = {}) => 
          Object.entries(obj).reduce((r, [key, val]) => {
            const k = `${prefix}${key}`
            if(typeof val === 'object'){ 
              flatten(val, `${k}.`, r)
            } else {
              res[k] = val
            }
            return r
          }, res)
         
        console.log(flatten(source))

        【讨论】:

          猜你喜欢
          • 2020-12-22
          • 2020-06-23
          • 1970-01-01
          • 2018-10-24
          • 2018-10-28
          • 2017-07-02
          • 1970-01-01
          • 2020-07-11
          • 2020-09-23
          相关资源
          最近更新 更多