【问题标题】:How to make a new structure in order to group based on value如何建立一个新的结构以便基于价值进行分组
【发布时间】:2018-11-03 22:24:54
【问题描述】:

我有以下 json:

[
    {
      'con': 'Usa',
      'city': 'ny',
      'town':'as'
    },
    {
      'con': 'Ger',
      'city': 'ber',
      'town':'zd'
    },
    {
      'con': 'Usa',
      'city': 'la',
      'town':'ss'
    }
  ]

并且我想将此 json 重新创建为新结构,以便不具有相同的 'con' 值,新结构应如下所示:

[{
        "con": "usa",
        "area": [{
            "city": "ny",
            "town": "as"
        }, {
            "city": "la",
            "town": "ss"
        }]
    },
    {
        "con": "ger",
        "area": [{
            "city": "ber",
            "town": "zd"
        }]
    }
]

你知道怎么做吗?谢谢

【问题讨论】:

标签: javascript arrays json sorting object


【解决方案1】:

另一种方法是使用函数Array.prototype.reducecountry 进行分组,同时使用函数Object.values 来提取分组的对象。

let arr = [{    'con': 'Usa',    'city': 'ny',    'town': 'as'  },  {    'con': 'Ger',    'city': 'ber',    'town': 'zd'  },  {    'con': 'Usa',    'city': 'la',    'town': 'ss'  }],
    result = Object.values(arr.reduce((a, {con, ...rest}) => {
      (a[con] || (a[con] = {con, area: []})).area.push(rest);
      return a;
    }, Object.create(null)));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

    猜你喜欢
    • 2016-02-12
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    • 2019-07-14
    • 2014-10-31
    • 1970-01-01
    • 2020-11-10
    相关资源
    最近更新 更多