从javascript中的对象数组中删除重复值

从javascript中的对象数组中删除重复值

本文介绍了从javascript中的对象数组中删除重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的对象数组:

i have an array of objects like this:

arr = [
    {label: Alex, value: Ninja},
    {label: Bill, value: Op},
    {label: Cill, value: iopop}
]

此数组在渲染我的react组件时组成。 i用户 Array.prototype.unshift 用于在数组顶部添加所需元素。
所以我写 arr.unshift({label:All,value:All})。当我的组件首次渲染时,我的数组成功创建了我想要的。但是当我重新渲染它时,它会向我显示值为 {label:All,value:All} 的数组。更具体地说,它显示如下:

This array is composed when my react component is rendered. The i user Array.prototype.unshift for adding a desired element in the top of my array.So i write arr.unshift({label: All, value: All}). When my component first rendered my array is successfully created as i desire. But when i rerender it it shows me the array with the value {label: All, value: All} as duplicate. To be more specific it is shown something like this:

arr = [
    {label: All, value: All},
    {label: All, value: All},
    {label: Alex, value: Ninja},
    {label: Bill, value: Op},
    {label: Cill, value: iopop}
]

我该如何解决这个问题?我在这里尝试了特定主题中描述的方法,但它没有用

How can i fix this? I tried the methods described in a specific topic here but it didn't work

推荐答案

你可以使用 array#reduce array#some

const arr = [
    {label: 'All', value: 'All'},
    {label: 'All', value: 'All'},
    {label: 'Alex', value: 'Ninja'},
    {label: 'Bill', value: 'Op'},
    {label: 'Cill', value: 'iopop'}
]

var result = arr.reduce((unique, o) => {
    if(!unique.some(obj => obj.label === o.label && obj.value === o.value)) {
      unique.push(o);
    }
    return unique;
},[]);
console.log(result);

这篇关于从javascript中的对象数组中删除重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 00:41