标签:
1 var arr = [{ 2 "id": 1, 3 "name": "内存", 4 "sid": 1, 5 "sname": "16G" 6 }, { 7 "id": 1, 8 "name": "内存", 9 "sid": 2, 10 "sname": "32G" 11 }, { 12 "id": 2, 13 "name": "颜色", 14 "sid": 5, 15 "sname": "白色" 16 }, { 17 "id": 2, 18 "name": "颜色", 19 "sid": 6, 20 "sname": "金色" 21 }, { 22 "id": 2, 23 "name": "颜色", 24 "sid": 7, 25 "sname": "黄色" 26 }];
今天做商城后台管理系统,后台传过来以上格式的数据。大概意思就是,商品的某一个属性,例如“内存”,对应N种具体的数值。我需要将数据拼装成如下的格式:
{ "1": { "id": "1", "name": "内存", "res": [{ "id": 1, "name": "内存", "sid": 1, "sname": "16G" }, { "id": 1, "name": "内存", "sid": 2, "sname": "32G" }] }, "2": { "id": "2", "name": "颜色", "res": [{ "id": 2, "name": "颜色", "sid": 5, "sname": "白色" }, { "id": 2, "name": "颜色", "sid": 6, "sname": "金色" }, { "id": 2, "name": "颜色", "sid": 7, "sname": "黄色" }] } }
这样我就可以进行for in遍历这个大的对象,操作每个属性的res属性中的数组数据进行遍历,最终每一行展现如“颜色:白色,金色,黄色”格式的数据。
最近脑子实在是不够用,最后在经理的教导下,顺利写了出了,方法如下:
var outObj = {}; for (var i = 0, len = arr.length; i < len; i++) { var tmp = arr[i]; if (!outObj.hasOwnProperty(tmp.sku_param_id)) { outObj[tmp.sku_param_id] = {}; var inObj = {}; var inArr = []; inObj["id"] = tmp.sku_param_id; inObj["name"] = tmp.param_web_name; inArr.push(tmp); inObj["res"] = inArr; outObj[tmp.sku_param_id] = inObj; } else { var inObj = outObj[tmp.sku_param_id]; var inArr = inObj["res"]; inArr.push(tmp); inObj["res"] = inArr; } }
标签:
原文地址:http://www.cnblogs.com/huangguaxiaocai/p/5055680.html