使用“colums”将JSON“行”组合到新对象中

时间:2016-10-05 15:12:26

标签: javascript json

我有一个看起来像这样的JSON对象数组

 [
    {"PM":"Jane","e":"j@nunya.com","h":"15.00","w":"10/30/2016 12:00:00 AM","c":"John","p":"Happy Town USA"},
    {"PM":"Jane","e":"j@nunya.com","h":"11.00","w":"11/06/2016 12:00:00 AM","c":"John","p":"Happy Town USA"},
    {"PM":"Jill","e":"j@nunya.com","h":"21.00","w":"10/30/2016 12:00:00 AM","c":"John","p":"Sad Town USA"},
    {"PM":"Jill","e":"j@nunya.com","h":"12.00","w":"11/06/2016 12:00:00 AM","c":"John","p":"Sad Town USA"}
 ]

查看给定PM,e,p,c组合的所有“列”的数据,除w和h字段外,数据相同。我需要将这些数据转换为一个看起来像这样的新对象。

[
    {PM:"Jane",e:"j@nunya.com",c:"John",p:"Happy Town USA",
     Details:[{"w":"10/30/2016","h":"15.00"},{"w":"11/06/2016","h":"11.00"}]},
    {PM:"Jill",e:"j@nunya.com",c:"John",p:"Sad Town USA",
    Details:[{"w":"10/30/2016","h":"21.00"},{"w":"11/06/2016","h":"12.00"}]}
]

这有点像在SQL查询中从行创建列,遗憾的是我几乎无法控制源数据,因此这不是一个选项。

3 个答案:

答案 0 :(得分:2)

您希望使用reduce在JavaScript中完成这些类型的转换:

var arr = /* your array of objects goes here */;

var results = Object.values(arr.reduce(function(obj, row) {
  var pm = row.PM;

  // here we check to see if we already have an aggregator for that pm
  if (!obj[pm]) {
    obj[pm] = {
      PM: pm,
      e: row.e,
      c: row.c,
      p: row.p
      Details: []
    };
  }

  // now we need to add a record to the Details
  obj[pm].Details.push({ w: row.w, h: row.h });

  // common mistake using reduce is to forget 
  // to return the accumulator
  return obj;
}, {}));

您可以使用JSON.stringify转换回JSON字符串。请注意,Object.values尚未在每个JavaScript环境中实现,您可能需要对其进行填充。

答案 1 :(得分:1)



[\x00-\x7F]+




答案 2 :(得分:0)

仅限Java方法:这个问题对于快速解决方案来说听起来非常具有挑战性。我在这里使用我创建的Java Oson库获得了部分解决方案,这里是the source file

@Test
public void testTableMerge2() {
    List<Map> list = oson.readValue("rows2Columns.txt");

    Map<String, List> collected = new HashMap<>();

    for (Map map: list) {
        String key = (String) map.get("PM");
        List obj = collected.get(key);

        if (obj == null) {
            obj = new ArrayList();

            collected.put(key, obj);
        }

        obj.add(map);
    }

    Config config = merge.getConfig();
    config.numericValue = NUMERIC_VALUE.MERGE_UNIQUE;
    config.nonnumericalValue = NONNUMERICAL_VALUE.MERGE_UNIQUE;
    config.listValue = LIST_VALUE.MERGE_UNIQUE;

    Map<String, Object> results = new HashMap<>();

    for (String key: collected.keySet()) {
        results.put(key, merge.merge(collected.get(key)));
    }

    Collection result = results.values();

    // oson.pretty();
    String json = oson.serialize(result);

    String expected = "[{\"PM\":\"Jill\",\"e\":\"j@nunya.com\",\"h\":[\"21.00\",\"12.00\"],\"w\":[\"10/30/2016 12:00:00 AM\",\"11/06/2016 12:00:00 AM\"],\"c\":\"John\",\"p\":\"Sad Town USA\"},{\"PM\":\"Jane\",\"e\":\"j@nunya.com\",\"h\":[\"15.00\",\"11.00\"],\"w\":[\"10/30/2016 12:00:00 AM\",\"11/06/2016 12:00:00 AM\"],\"c\":\"John\",\"p\":\"Happy Town USA\"}]";

    assertEquals(expected, json);
}