在javascript中展平嵌套对象 [英] flattening the nested object in javascript

查看:70
本文介绍了在javascript中展平嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I ran into this problem, I was able to write solution which can handle array of object (not posted here) or one level deep nested object but i couldn't solve when the given object has nested structure like below. I am curious to know how we can solve this.

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 } } },我的尝试将失败.

But my attempt will fail if the object is like { foo: { boo : { doo : 1 } } }.

推荐答案

您应该能够使用递归相当简单地做到这一点.它的工作方式是,您仅递归地调用对象子代的解析器,该子代在向下添加正确的密钥.例如(虽然没有经过非常严格的测试):

You should be able to do it fairly simply with recursion. The way it works, is you just recursively call a parser on object children that prepend the correct key along the way down. For example (not tested very hard though):

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

这篇关于在javascript中展平嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆