我正在尝试根据将JSON分为多个数组type
,我当前的json是:
// current json file:
{
"res": [
{
"type" : "stream",
"price" : "3.99",
"id" : "13nee"
},
{
"type" : "stream",
"price" : "2.99",
"id" : "8ejwj"
},
{
"type" : "buy",
"price" : "3.99".
"id" : "9akwk"
},
...
]
}
我希望通过type
如下方式将其分类为多个数组:
var sorted = {
"stream" : [
{
"price" : "2.99",
"id" : "8ejwj"
},
{
"price" : ".99",
"id" : "13nee"
},
... // other objects with type: "stream"
],
"buy" : [
{
"price" : "3.99".
"id" : "9akwk"
},
... // other objects with type: "buy"
]
}
我已经尝试过了,但是我唯一能想到的解决方案是按大小写-如果循环运行,如果大小写匹配类型,则将对象推送到数组。有没有更优雅的解决方案?
var items = {};
var i = 0;
for(i; i < res.length; i += 1){
var resItem = res[i];
if(items.hasOwnProperty(resItem.type)){
items[resItem.type].push({price:resItem.price, id:resItem.id});
} else {
items[resItem.type] = [{price:resItem.price, id:resItem.id}];
}
}
JavaScript对象上的属性是经过哈希处理的,因此您可以像上面那样动态匹配并生成新对象。如果要应用排序良好的排序,则需要将其应用于新生成的items对象的数组。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句