多层嵌套对象实现key值连接展开

目标对象

var obj = {
  a: {
    info: {
       name: 'Joe',
       age: 18
    }
  },
  b: {
    hh: 'aadsf'
  }
}

处理后变成这样

var obj = {
  'a.info.name': 'Joe',
  'a.info.age': 18,
  'b.hh': 'aadsf'
}

如何实现呢,头大。。。

阅读 5.4k
5 个回答

不要头大,递归就解决了

const obj = {
    a: {
        info: {
            name: 'Joe',
            age: 18
        }
    },
    b: {
        hh: 'aadsf'
    }
}

function isObject(v) {
    // 这里只简单的判断了是不是对象,可能还需要判断数组等情况
    return typeof v === "object";
}

function flattern(v, parentKeys = []) {
    // 递归终止条件:如果 v 不是对象,直接返回 { path: v }
    if (!isObject(v)) {
        return { [parentKeys.join(".")]: v }
    }

    // 是对象的话,递归映射 ⇐ ❶。注意 flattern() 返回的是一个展平的对象
    const subs = Object.entries(v)
        .map(([key, value]) => flattern(value, [...parentKeys, key]));

    // flattern() 要返回一个展平的对象,
    // 而 subs 是多个(当前 v 每个属性对应一个)展平的对象,
    // 当然需要合并成一个返回去的 ⇒ ❶
    return Object.assign({}, ...subs);
}

const r = flattern(obj);

console.log(JSON.stringify(r, null, 2));

简单写了个嵌套


function flat (obj) {
  let newObj = {}

  function process (subObj, prefixArr) {
    for (let k in subObj) {
      let newArr = prefixArr.concat()
      newArr.push(k)
      if (Object.prototype.toString.call(subObj[k]) === '[object Object]') {
        process(subObj[k], newArr)
      } else {
        newObj[newArr.join('.')] = subObj[k]
      }
    }
  }
  process(obj, [])
  return newObj
}

let ret = flat(obj)

console.log(ret)
  const isObject = (val) => typeof val  === 'object'

  function solution(obj, group = [], result = {}) {
    Object.keys(obj).forEach(key => {
        const val = obj[key]
        const newGroup = group.slice()
        newGroup.push(key)

        if (isObject(val)) {
            solution(obj[key], newGroup, result)
        } else {
            const groupKey = [...newGroup].join('.')
            result[groupKey] = val
        }
    })
    return result
  }
  
  const r = solution(obj)
  console.log('r: ', r);
var flatten = function fn(obj, keys = []) {
    return Object.keys(obj).reduce((current, next) => {
        return Object.assign({}, current, Object.prototype.toString.call(obj[next]) === '[object Object]' ?
            fn(obj[next], keys.concat([next])) : { [keys.concat([next]).join(".")]: obj[next] })
    }, {})
}
var obj = {
            a: {
                info: {
                    name: 'Joe',
                    age: 18
                }
            },
            b: {
                hh: 'aadsf'
            },
            c: [4, 6]
        };
        var res = (function toArr(obj, kyes = []) {
            return Object.entries(obj).reduce(
                (acc, [key, val]) => 
                    Object.assign(
                        acc, val instanceof Object ? 
                            toArr(val, kyes.concat(key)) : 
                            {[kyes.concat(key).join('.')]: val}), 
                {})
        })(obj);
        console.log(res);
        /*
{
a.info.age: 18,
a.info.name: "Joe",
b.hh: "aadsf",
c.0: 4,
c.1: 6
}
        */
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题