问题
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