按键读取并解析为JSON

时间:2015-08-26 10:02:57

标签: javascript json

如果我有以下JSON数组:

[
    {"data":
        [
            {"W":1,"A1":"123"},
            {"W":1,"A1":"456"},
            {"W":2,"A1":"4578"},
            {"W":2,"A1":"2423"},
            {"W":2,"A1":"2432"},
            {"W":2,"A1":"24324"}
        ]
    }
]

如何将其转换为:

[
    {"1":[
        {"A1":"123"},
        {"A1":"456"}
    ]},
    {"2":[
        {"A1":"4578"},
        {"A1":"2423"},
        {"A1":"2432"},
        {"A1":"24324"}
    ]}
]

3 个答案:

答案 0 :(得分:0)

您可以使用underscore

  

groupBy_.groupBy(list,iteratee,[context])

     

将集合拆分为集合,按照通过iteratee运行每个值的结果进行分组。如果iteratee是一个字符串而不是一个函数,则按每个值的iteratee命名的属性进行分组。

_.groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); });
=> {1: [1.3], 2: [2.1, 2.4]}

_.groupBy(['one', 'two', 'three'], 'length');
=> {3: ["one", "two"], 5: ["three"]}

答案 1 :(得分:0)

所以基本上做一些减少:



var obj = [{
        "data": [
            { "W": 1, "A1": "123" },
            { "W": 1, "A1": "456" },
            { "W": 2, "A1": "4578" },
            { "W": 2, "A1": "2423" },
            { "W": 2, "A1": "2432" },
            { "W": 2, "A1": "24324" }
        ]
    }],
    grouped = obj[0].data.reduce(function (r, a) {
        r[a.W] = r[a.W] || [];
        r[a.W].push({ A1: a.A1 });
        return r;
    }, {}),
    groupedAsDesired = Object.keys(grouped).reduce(function (r, a) {
        var o = {};
        o[a] = grouped[a];
        r.push(o);
        return r;
    }, []);

document.write('<pre>grouped: ' + JSON.stringify(grouped, 0, 4) + '</pre>');
document.write('<pre>groupedAsDesired: ' + JSON.stringify(groupedAsDesired, 0, 4) + '</pre>');
&#13;
&#13;
&#13;

一个小提示,没有必要在数组中包含具有不同属性的对象,例如您想要的结果。请查看结果窗口中的差异:grouped vs groupedAsDesired

答案 2 :(得分:0)

您可以在原生Javascript中执行此操作,并遵循功能方式,这种方式更趋于性感,更短。要处理此问题,您可以模拟 hashmap 键/值。

您可以使用强大的Array.prototype.reduce()Array.prototype.concat()方法。

      //Concat reduce result to an array
  //We initialize our result process with an empty object
  var filter = [].concat.apply(array[0].data.reduce(function(hash, current){
      //If my hashmap get current.W as key
      return hash.hasOwnProperty(current.W)
      //push our current object to our map, and return the hashmap
      ? (hash[current.W].push({'A1': current.A1}), hash)
      //otherwise, create an hashmap key with an array as value, and return the hashmap
      : (hash[current.W] = [{'A1': current.A1}], hash);
  }, {}));

  console.log(filter);