在JavaScript中,我需要知道对象数组是否至少包含两个相同的对象。
我有一个表格,允许人们创建问题(标题,描述,类型,答案选项)。我需要检查用户是否输入了带有相同标签的多个答案选项。它们存储在数组中。
// The array of answer options
let array = [{value: 'a'}, {value: 'b'}, {value: 'c'}, {value: 'a'}]
我尝试使用array.indexOf({value: 'a'})
和array.lastIndexOf({value: 'a'})
,但它们的索引都为-1。
答案 0 :(得分:1)
单独的对象永远不会相互===
,因此您必须使用其他方法。一种选择是创建一组字符串化对象,并在找到任何重复的字符串后返回true:
const hasDupes = (arr) => {
const strings = new Set();
for (const obj of arr) {
const string = JSON.stringify(obj);
if (strings.has(string)) {
return true;
}
strings.add(string);
}
return false;
};
console.log(hasDupes([{value: 'a'}, {value: 'b'}, {value: 'c'}, {value: 'a'}]));
console.log(hasDupes([{value: 'a'}, {value: 'b'}, {value: 'c'}]));
答案 1 :(得分:1)
如果您只关心value
属性,并且用例并不复杂,则可以通过以下方法简单地在一行中完成此操作:
let hasDupes = arr => new Set(arr.map(x => x.value)).size !== arr.length
console.log(hasDupes([{value: 'a'}, {value: 'b'}, {value: 'c'},{value: 'a'}]))
console.log(hasDupes([{value: 'a'}, {value: 'b'}, {value: 'c'}]))
您将使用Set来添加value
的值,并且如果它的大小小于实际输入数组的长度,并且小于重复项。如果只关心被检查的一个属性,则无需执行JSON.stringify
,比较字符串等。
也JSON.stringify has issues when comparing equality of objects。
答案 2 :(得分:0)
使用findIndex
:
let array = [{value: 'a'}, {value: 'b'}, {value: 'c'}, {value: 'a'}];
const index = array.findIndex(({ value }) => value == "a");
console.log(index);
答案 3 :(得分:0)
indexOf将返回对象的实例
{value: 'a'} !== {value: 'a'};
因为它们都是对象的不同实例。
您可以找到对象
const obj = array.find(item => item.value === 'a')
答案 4 :(得分:0)
您可以使用lodash.js比较两个对象。 请参阅下面的示例。
let array = [{ value: "a" }, { value: "b" }, { value: "c" }, { value: "a" }];
const object = { value: "a" };
countObjOccurrences = object => {
let occurances = 0;
array.map(item => {
if (_.isEqual(item, object)) {
occurances += 1;
}
});
return occurances;
};
此函数将返回2。