数组分离
有这样一种需求,如何将一个数组,根据数组中的某一个键值,将这个原有数组, “分类” 组成一个新的数组?
话不多说,直入主题 ^ _ ^ !:
原数组:
oldArr = [{"cateName":"硬盘","cateIndex":0,"goodsId":"1","goodsAttr":"三星/机械硬盘"},
{"cateName":"硬盘","cateIndex":0,"goodsId":"4","goodsAttr":"三星/固态硬盘"},
{"cateName":"硬盘","cateIndex":0,"goodsId":"5","goodsAttr":"三星/机械硬盘"},
{"cateName":"内存","cateIndex":1,"goodsId":"2","goodsAttr":"金士顿/DDR11"},
{"cateName":"内存","cateIndex":1,"goodsId":"6","goodsAttr":"金士顿/DDR11"},
{"cateName":"主板","cateIndex":2,"goodsId":"59","goodsAttr":"123"},
{"cateName":"显示器","cateIndex":3,"goodsId":"64","goodsAttr":"123223"}];
期望结果:
newArr = [[{"cateName": "硬盘", "cateIndex": 0, "goodsId": "1", "goodsAttr": "三星/机械硬盘"},
{"cateName": "硬盘", "cateIndex": 0, "goodsId": "4", "goodsAttr": "三星/固态硬盘"},
{"cateName": "硬盘", "cateIndex": 0, "goodsId": "5", "goodsAttr": "三星/机械硬盘"}],
[{"cateName": "内存", "cateIndex": 1, "goodsId": "2", "goodsAttr": "金士顿/DDR11"},
{"cateName": "内存", "cateIndex": 1, "goodsId": "6", "goodsAttr": "金士顿/DDR11"}],
[{"cateName": "主板", "cateIndex": 2, "goodsId": "59", "goodsAttr": "123"}],
[{"cateName": "显示器", "cateIndex": 3, "goodsId": "64", "goodsAttr": "123223"}]]
接下来,就是 magic time:
// 数组根据某一值分成多个数组
function likSeparateArr(arr, str) {
var strArr = [];
$.each(arr, function (i, v) {
if ($.inArray(v[str], strArr) == -1) {
strArr.push(v[str]);
}
});
var newArr = [];
$.each(strArr, function (i, v) {
var childrenArr = [];
$.each(arr, function (i2, v2) {
if (v2[str] == v) {
childrenArr.push(v2);
}
});
newArr.push({
parent: v,
children: childrenArr
})
});
return newArr;
}
最终结果如下:
[
{
"parent": "硬盘",
"children": [
{"cateName": "硬盘", "cateIndex": 0, "goodsId": "1", "goodsAttr": "三星/机械硬盘"},
{"cateName": "硬盘", "cateIndex": 0, "goodsId": "4", "goodsAttr": "三星/固态硬盘"},
{"cateName": "硬盘", "cateIndex": 0, "goodsId": "5", "goodsAttr": "三星/机械硬盘"}
]
},
{
"parent": "内存",
"children": [
{"cateName": "内存", "cateIndex": 1, "goodsId": "2", "goodsAttr": "金士顿/DDR11"},
{"cateName": "内存", "cateIndex": 1, "goodsId": "6", "goodsAttr": "金士顿/DDR11"}
]
},
{
"parent": "主板",
"children": [
{"cateName": "主板", "cateIndex": 2, "goodsId": "59", "goodsAttr": "123"}
]
},
{
"parent": "显示器",
"children": [
{"cateName": "显示器", "cateIndex": 3, "goodsId": "64", "goodsAttr": "123223"}
]
}
]
有任何疑问或者建议,就给我留言吧!
author:Lik
Endeavoring to powerless, struggling to move yourself.
Endeavoring to powerless, struggling to move yourself.