在Javascript/React Native中,可以使用以下方法删除对象数组中具有两个重复字段的一个。
首先,假设我们有一个包含对象的数组,对象具有两个重复字段:field1和field2。
const array = [
{ field1: 'value1', field2: 'value2', otherField: 'otherValue' },
{ field1: 'value3', field2: 'value4', otherField: 'otherValue' },
{ field1: 'value1', field2: 'value2', otherField: 'otherValue' },
{ field1: 'value5', field2: 'value6', otherField: 'otherValue' }
];
const newArray = array.filter((obj, index, self) => {
const firstIndex = self.findIndex(
item => item.field1 === obj.field1 && item.field2 === obj.field2
);
return index === firstIndex;
});
在上面的示例中,newArray将是一个仅包含了第一个重复字段的对象的新数组。
const array = [
{ field1: 'value1', field2: 'value2', otherField: 'otherValue' },
{ field1: 'value3', field2: 'value4', otherField: 'otherValue' },
{ field1: 'value1', field2: 'value2', otherField: 'otherValue' },
{ field1: 'value5', field2: 'value6', otherField: 'otherValue' }
];
array.forEach((obj, index, self) => {
const firstIndex = self.findIndex(
item => item.field1 === obj.field1 && item.field2 === obj.field2
);
if (index !== firstIndex) {
self.splice(index, 1);
}
});
在上面的示例中,array将是一个已经删除了重复字段的对象的原始数组。
以上是删除对象数组中具有两个重复字段中的一个的方法。希望对你有帮助!
领取专属 10元无门槛券
手把手带您无忧上云