在操作json数组时get到一个新的知识点,利用filter()进行判断得到新的json数组然后在用map()进行整合出自己想要的数据结构;
实现效果:(如图)
购物车页面为list,通过里面的selected来判断是否选中,点击购买时获取想要的一些数据进行交互,比如商品id,规格,购买数量
1、整个购物车的数据结构:
list:[
{
id:1560,
selected: true, //通过判断来操作是否选中状态
shopping_image: '/static/shopImage.png',
shopping_title:'养生枸杞银耳汤',
shopping_time:'取货时间:8月1日-8月5日',
shopping_number:'已团购246/剩余50',
sy_number: 10,
price:8.55,
listGuige:{
color:['白色','黑色'],
zhongliang:['8kg','10kg'],
size:['S','M'],
cindex:0,
zindex:1,
sindex:0
},
num:1
},{
id:1890,
selected: true,
shopping_image: '/static/shopImage.png',
shopping_title:'养生枸杞银耳汤',
shopping_time:'取货时间:8月1日-8月5日',
shopping_number:'已团购246/剩余80',
sy_number: 80,
price:9.5,
listGuige:{
color:['白色','黑色'],
zhongliang:['8kg','10kg'],
size:['S','M'],
cindex:0,
zindex:1,
sindex:1
},
num:4
},{
id:182,
selected: true,
shopping_image: '/static/shopImage.png',
shopping_title:'养生枸杞银耳汤',
shopping_time:'取货时间:8月1日-8月5日',
shopping_number:'已团购246/剩余120',
sy_number: 10,
price:10.55,
listGuige:{
color:['白色','黑色'],
zhongliang:['8kg','10kg'],
size:['S','M'],
cindex:1,
zindex:1,
sindex:0
},
num:8
}
],
2、正常js操作json数组
let that = this;
let list = that.data.list;
let newshopList;
for(let i=0;i<list.length;i++){ //通过for循环操作数组
if(list[i].selected){ //判断当前商品是否选中状态,true的时候,获取需要只
newshopList[i] = {
id:list[i].id,
num:list[i].num,
listGuige:list[i].listGuige
}
// newshopList[i].num = list[i].num
// newshopList[i].listGuige = list[i].listGuige
//注:不可这样写,即使上面有声明newshopList的类型,i=0的时候不会有问题,但是后面就会有问题,因为循环时后面格式不对
}
}
console.log("循环里newshopList:",newshopList)
3、通过*.filter()执行判断条件去掉不符合项,然后通过*.map()进行数组迭代获得需要的数据
//es5写法 item
//判断条件去掉未选中项的数据
let newList = list.filter(function(item){
return item.selected === true;
})
let newshopList = newlist.map(function(item){
return {
id:item.id,
num:item.num,
listGuige:item.listGuige
}
})
//es6写法
//判断条件去掉未选中项的数据
let newList = list.filter(item => item.selected === true)
let newshopList = newList.map(item => ({id:item.id,num:item.num,listGuige:item.listGuige}))
4、利用*.filter()去掉数组中的空字符串,undefined,null等值
//空字符串不能包含空格
let arr=['1','2','3',' ','',null,undefined];
console.log(arr.filter(item => item))
//返回 ['1','2','3',' ']
5、利用*.filter进行数组去重
var arr = [1, 2, 2, 3, 4, 5, 5, 6, 7, 7];
//es5
var arr2 = arr.filter(function(x,index,self){
return self.indexOf(x)===index
})
//es6
var arr2 = arr.filter((x, index,self)=>self.indexOf(x)===index)
console.log(arr2); //[1, 2, 3, 4, 5, 6, 7]
index代表传入元素的下标,self代表函数本身,indexOf始终返回第一次找到匹配该元素的索引
6、json数组去重,利用reduce方法遍历数组,reduce第一个参数是遍历需要执行的函数,第二个参数是item的初始值
var arr = [{
id: '1',
value: '1'
}, {
id: '2',
value: '2'
}, {
id: '3',
value: '3'
},{
id: '4',
value: '4'
},{
id: '1',
value: '1'
}];
let obj = {};
const arr1 = arr.reduce(function(item,next) {
obj[next.id] ? '' : (obj[next.id] = true && item.push(next));
return item;
}, []);
console.log(arr1)