一根衬板将嵌套的对象弄平 [英] One liner to flatten nested object

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

问题描述

我需要展平嵌套对象.需要一个衬板.不确定此过程的正确术语是什么. 我可以使用纯Javascript或库,尤其喜欢下划线.

I need to flatten a nested object. Need a one liner. Not sure what the correct term for this process is. I can use pure Javascript or libraries, I particularly like underscore.

我有...

{
  a:2,
  b: {
    c:3
  }
}

我想要...

{
  a:2,
  c:3
}

我已经尝试过...

var obj = {"fred":2,"jill":4,"obby":{"john":5}};
var resultObj = _.pick(obj, "fred")
alert(JSON.stringify(resultObj));

哪个工作,但我也需要这个工作...

Which works but I also need this to work ...

var obj = {"fred":2,"jill":4,"obby":{"john":5}};
var resultObj = _.pick(obj, "john")
alert(JSON.stringify(resultObj));

推荐答案

在这里:

Object.assign({}, ...function _flatten(o) { return [].concat(...Object.keys(o).map(k => typeof o[k] === 'object' ? _flatten(o[k]) : ({[k]: o[k]})))}(yourObject))

摘要:递归地创建一个包含一个属性的对象的数组,然后将它们全部与Object.assign组合.

Summary: recursively create an array of one-property objects, then combine them all with Object.assign.

这使用了包括Object.assign或扩展运算符在内的ES6功能,但是应该很容易重写而不要求它们.

This uses ES6 features including Object.assign or the spread operator, but it should be easy enough to rewrite not to require them.

对于那些不关心单行疯狂​​并希望能够实际阅读的人(取决于您对可读性的定义):

For those who don't care about the one-line craziness and would prefer to be able to actually read it (depending on your definition of readability):

Object.assign(
  {}, 
  ...function _flatten(o) { 
    return [].concat(...Object.keys(o)
      .map(k => 
        typeof o[k] === 'object' ?
          _flatten(o[k]) : 
          ({[k]: o[k]})
      )
    );
  }(yourObject)
)

这篇关于一根衬板将嵌套的对象弄平的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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