码迷,mamicode.com
首页 > 编程语言 > 详细

数组分离

时间:2017-06-29 19:15:10      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:数组   如何   att   return   多个   根据   sep   each   固态硬盘   

有这样一种需求,如何将一个数组,根据数组中的某一个键值,将这个原有数组, “分类”  组成一个新的数组?

话不多说,直入主题  ^ _ ^ !:

原数组:

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


有任何疑问或者建议,就给我留言吧!

数组分离

标签:数组   如何   att   return   多个   根据   sep   each   固态硬盘   

原文地址:http://www.cnblogs.com/likwin/p/7095840.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!