使用linq.js从多个对象创建JSON对象数组

时间:2015-02-25 18:04:50

标签: javascript linq.js

我有一个像这样的JSON数组:

var jsonArray = [
    { Date: "2010-02-25", Size:"Large", Type:"a", Value: "100"},
    { Date: "2010-02-25", Size:"Medium", Type:"a", Value: "160"},
    { Date: "2010-02-25", Size:"Small", Type:"a", Value: "200"},
    { Date: "2010-02-25", Size:"Large", Type:"b", Value: "400"},
    { Date: "2010-02-25", Size:"Medium", Type:"b", Value: "120"},
    { Date: "2010-02-25", Size:"Small", Type:"b", Value: "170"}
]

我一直在使用linq.js,我试图操纵上面的JSON,所以6个对象变成2,所以我留下了一个像下面的数组:

var desiredArray = [

    { Date: "2010-02-25", Large:"100", Medium: "160", Small: "200", Type:"a" }
    { Date: "2010-02-25", Large:"400", Medium: "120", Small: "170", Type:"b" }

]

但这是我第一次使用linq。我花了很长时间试图解决它,但我真的不知道如何启动它。

有人能指出我正确的方向吗?

任何帮助都会非常感激

1 个答案:

答案 0 :(得分:2)

以下是实现此目标的一种方法:



var jsonArray = [
    { Date: "2010-02-25", Size:"Large", Type:"a", Value: "100"},
    { Date: "2010-02-25", Size:"Medium", Type:"a", Value: "160"},
    { Date: "2010-02-25", Size:"Small", Type:"a", Value: "200"},
    { Date: "2010-02-25", Size:"Large", Type:"b", Value: "400"},
    { Date: "2010-02-25", Size:"Medium", Type:"b", Value: "120"},
    { Date: "2010-02-25", Size:"Small", Type:"b", Value: "170"}
];

function makeGroupKey(item) {
    return JSON.stringify({
        Date: item.Date,
        Type: item.Type
    });
}

function mergeItems(items) {
    return items.Aggregate(JSON.parse(items.Key()), function (prev, next) {
        prev[next.Size] = next.Value;
        return prev;
    });
}

var result = Enumerable.From(jsonArray)
    .GroupBy(makeGroupKey)
    .Select(mergeItems)
    .ToArray();

console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.min.js"></script>
&#13;
&#13;
&#13;