[
{
"cid": "1",
"name": "图书",
"pid": "0",
"type": "1"
},
{
"cid": "2",
"name": "音像",
"pid": "0",
"type": "1"
},
{
"cid": "3",
"name": "电子书",
"pid": "0",
"type": "1"
},
{
"cid": "4",
"name": "家用电器",
"pid": "0",
"type": "2"
}
]
这是我的一段json 怎么用js 将type相等的分在一起 并且输出成一个数组
处理数组,遍历、筛选、排序、等。最好使用underscore.js类库。
var data = [...]; // 你的数据
var newData = data.filter(function (value) {
return value.type === '1';
});
通过自己的实践后,提供几个解决方案,看到底哪一个比较适合你,把选择权交给你,不符合要求,可以联系我。、
var foo=[
{
"cid": "1",
"name": "图书",
"pid": "0",
"type": "1"
},
{
"cid": "2",
"name": "音像",
"pid": "0",
"type": "1"
},
{
"cid": "3",
"name": "电子书",
"pid": "0",
"type": "1"
},
{
"cid": "4",
"name": "家用电器",
"pid": "0",
"type": "2"
}
]
解决方案:
// 可以用来把type类型数组输出
var jsontext= JSON.stringify(foo,["type"]);
console.log(jsontext);
var l= foo.length;
var arr4 =[]
for (var i = 0; i < l; i++) {
if(foo[i].type== '1'){
console.log(foo[i]);
arr4[i]= foo[i];
console.log(arr4[i]);
}
};
// 利用underscore.js 输出
var ud= _.filter(foo,function(e){
if (e.type=='1') {
console.log(e);
};
});
代码详细
filter
并不能分组,自己写个循环来处理就是了
var list = [{
"cid": "1",
"name": "图书",
"pid": "0",
"type": "1"
}, {
"cid": "2",
"name": "音像",
"pid": "0",
"type": "1"
}, {
"cid": "3",
"name": "电子书",
"pid": "0",
"type": "1"
}, {
"cid": "4",
"name": "家用电器",
"pid": "0",
"type": "2"
}];
// 保存 type 到 items 数组的映射表
var types = {};
// 按 list 中 type 的顺序生成新的列表
// 每个元素都是一个 { type, items }
var newList = [];
list.forEach(function(item) {
var typeItems = types[item.type];
// typeItems 无值说明映射表里还没加入这个 type
if (!typeItems) {
// 产生一个新的 items 列表
typeItems = [];
// 将 type 这个 items 列表加入映射表
types[item.type] = typeItems;
// 因为是个新的 type,所以加入 newList
newList.push({
type: item.type,
items: typeItems
});
}
// 这里 items 就是按类型找到的元素组
// 在 items 中加入当前 item
typeItems.push(item);
});
console.log(newList);
结果(JSON表示)
[{
"type": "1",
"items": [{
"cid": "1",
"name": "图书",
"pid": "0",
"type": "1"
}, {
"cid": "2",
"name": "音像",
"pid": "0",
"type": "1"
}, {
"cid": "3",
"name": "电子书",
"pid": "0",
"type": "1"
}]
}, {
"type": "2",
"items": [{
"cid": "4",
"name": "家用电器",
"pid": "0",
"type": "2"
}]
}]
如果要按类型取 name
列表
从上面得到的 newList 开始
var lines = newList.map(function(type) {
var names = type.items.map(function(item) {
return item.name;
});
return "type[" + type.type + "] - " + names.join(", ");
});
lines 的结果(JSON表示)
[
"type[1] - 图书, 音像, 电子书",
"type[2] - 家用电器"
]
看例子,你可以自由发挥。
var foo=[
{
"cid": "1",
"name": "图书",
"pid": "0",
"type": "1"
},
{
"cid": "2",
"name": "音像",
"pid": "0",
"type": "1"
},
{
"cid": "3",
"name": "电子书",
"pid": "0",
"type": "1"
},
{
"cid": "4",
"name": "家用电器",
"pid": "0",
"type": "2"
}
]
var b=foo.filter(function(v){
return v["type"]==="1"
})
数组的filter方法,兼容性的话你可以自己瞧瞧