Creat array of JSON objects from mulitple objects using linq.js

感情迁移 提交于 2019-12-25 08:45:07

问题


I have a JSON array like so:

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"}
]

I have been using linq.js and I am trying to manipulate the above JSON so the 6 objects are turned into 2, so I am left with an Array like below:

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" }

]

But this is the first time I have ever used linq. I have spent quite a while trying to figure it out but I really dont know how to start it.

Could anyone point me in the right direction?

Any help would be really appreciated


回答1:


Here's one way to accomplish this:

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>


来源:https://stackoverflow.com/questions/28726394/creat-array-of-json-objects-from-mulitple-objects-using-linq-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!