数组去重之【数组内对象去重】(其一)

首先得到一组需要去重的数组

toUp:[
	{questionId:1,selectContent:'满意'},
	{questionId:2,selectContent:'满意'},
	{questionId:3,selectContent:'一般'},
	{questionId:4,selectContent:'较满意'},
	{questionId:5,selectContent:'不满意'},
	{questionId:5,selectContent:'一般'},
	{questionId:6,selectContent:'满意'}
]

通常会想到的方法是,用for()循环遍历,用forEach()
这样的思路是对的,至少大方向没错。

方法一:利用对象访问属性的方法,判断对象中是否存在questionId

  1. 声明一个空数组,用于存放新内容。
  2. 声明一个空对象,用于做判断。
export default {
	data() {
		return {
			toUp:[],
			toUps: [],
            object:{}
		}
	}
}

next for() star,那么遍历开始

this.toUp.push({questionId:index+1,selectContent:num==1?'满意':num==2?'较满意':num==3?'一般':num==4?'不满意':''})//将每一题的题号、题目、选项 加到数组toUp中提交。
for(let i=0;i<this.toUp.length;i++) {
    if(!this.object[this.toUp[i].questionId]) {
        this.toUps.push(this.toUp[i]);
        this.object[this.toUp[i].questionId] = true;
    }
}
console.log(this.toUps)//保证不重复出现相同题号的

方法二:利用reduce方法遍历数组,reduce第一个参数是遍历需要执行的函数,第二个参数是item的初始值

this.toUp = this.toUp.reduce(function(item, next) {
    obj[next.questionId] ? '' : obj[next.questionId] = true && item.push(next);
    return item;
}, []);
console.log(this.toUp); 

猜你喜欢

转载自blog.csdn.net/Allanwhy/article/details/89463613