数组中相同的两个对象,使用reduce + hash去重。

229 阅读1分钟

在页面的渲染过程中,有时候在store中循环处理数据的时候。回有两条相同的数据,这时候页面中的渲染肯定会出现两条数据。这时候注意到了reduce方式去重功能。简直完美至极

直接定义然后使用的相同的方式,会得到你意想不到效果。

pages: {

            handler(newValue) {
                if (newValue) {
                    this.addQuestion = JSON.parse(JSON.stringify(newValue))
                    console.log('question', this.addQuestion)
                    this.addQuestion.forEach((item, index) => {
                        let hash = {};
                        item.questionData = item.questionData.reduce((preVal, curVal) => {
                            hash[curVal.id] ? '' : hash[curVal.id] = true && preVal.push(curVal);
                            return preVal
                        }, [])
                    })
                }
            },
            deep: true,
            immediate: true
        }
        
        
        
        直接代码复制过去就ok,核心是定义hash的开始。