问题描述
我有一个像这样的对象数组:
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中的对象数组中删除重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!