检查数组是否包含值

问题描述 投票:1回答:7

我有一个对象数组,我需要防止重复的对象被添加到数组中。我尝试了以下代码来检查重复项:

const array = [{ name: 'John' }];

const newName = {
  name: 'John'
};
console.log(array);
console.log(newName);

if (array.includes(newName)) {
  console.log(newName.name + ' exists');
} else {
  console.log('name does not exist');
}

控制台日志记录告诉对象NewName与array [0]完全相同。然而,

if(array.includes(newName))

返回false。

我做错了什么?我在这篇文章中尝试了解决方案,但没有运气:

How do I check if an array includes an object in JavaScript?

javascript arrays object
7个回答
3
投票

如果name是对象的标识,则可以在数组上使用some函数:

const array = [{ name: 'John' }];    
const newName = { name: 'John' };

if (array.some(({name}) => name === newName.name)) {
  console.log(newName.name + ' exists');
} else {
  console.log('name does not exist');
}

或者您可以检查属性的数量是否相同,然后检查每个属性是否:

const array = [{ name: 'John', age: 33 }, { name: 'John', age: 45 }];    
const newName = { age: 33, name: 'John' };

if (array.some(x => Object.keys(x).length === Object.keys(newName).length && Object.keys(x).every(p => x[p] === newName[p]))) {
  console.log(newName.name + ' exists');
} else {
  console.log('name does not exist');
}

4
投票

简单地说,你可以使用array.someArray.prototype.some() documentation

在您自己的示例中,您可以对您的程序进行一些调整:

const array = [{ name: "John" }];

  const newName = {
    name: "John"
  };
  console.log(array);
  console.log(newName);

  if (array.some(object => object.name === newName.name)) {
    console.log(newName.name + " exists");
  } else {
    console.log("name does not exist");
  }

3
投票

您缺少的是includes在对象上使用它时会检查身份。 newName具有与数组中对象相同的属性,但它不是同一个对象,只有两个名为John的人是同一个人。有一个更明显的例子,运行{} == {},你会得到false

要检查数组是否包含具有相同名称的对象,可以使用some并将其传递给比较对象的函数,例如

array.some(e => e.name == newName.name)

2
投票

用它 :

var newName = {
 name: 'John'
};
console.log(array);
console.log(newName.name);
var found = array.some(obj => obj.name === newName.name);

if (found) {
 console.log(newName.name + ' exists');
} else {
 console.log('name does not exist');
}

1
投票

const array = [{
  name: 'John'
}];

const newName = {
  name: 'John'
};

let resultArr = array.filter((item) => {
  return item.name === newName.name
})

let elementPresentMsg;

if (resultArr.length > 0) {
  elementPresentMsg = newName.name + ' exists';
} else {
  elementPresentMsg = 'name does not exist'
}

document.getElementById('msg').innerHTML = elementPresentMsg;
<html>

<body>

  <p id="msg"></p>

</body>

</html>

如果要从数组中查找名称或任何其他值,如果对象的属性与对象数组中的属性相同,则以下内容应该会有所帮助:

const array = [{ name: 'John' }];

const newName = {
  name: 'John'
};

let resultArr = array.filter((item) => {
    return item.name === newName.name
})

if (resultArr.length > 0) {
  alert(newName.name + ' exists'); //any way to print result instead of alert
} else {
  alert('name does not exist'); //any way to print result instead of alert
}

0
投票

那是因为array[0]不等于newName。在Javascript中,它们指向不同的元素。你可以尝试console.log(array[0] == newName),你会得到false。 如果要查找重复项,可以尝试这样:

if (JSON.stringify(array).indexOf(JSON.stringify(newName)) != -1) {
  console.log('exist')
}
else {
  console.log('not exist')
}

0
投票

这是因为您正在尝试比较永远不会相等的两个不同的对象实例。

但是如果通过执行JSON.stringify将对象转换为原始字符串,则可以使用Array.includes进行深度比较。正如ttulka指出的那样,只有当要搜索的对象具有与要在数组中查找的对象相同的顺序的属性时,这才有效。

const array = [{ name: 'John', age: 33 }];
const newName = {
  name: 'John',
  age: 33
};
if (array.map(obj => JSON.stringify(obj)).includes(JSON.stringify(newName))) {
  console.log(newName.name + ' exists');
} else {
  console.log('name does not exist');
}

如果你在MDN中查看Array#includes polyfill,你会看到使用===严格相等运算符进行比较:

function sameValueZero(x, y) {
   return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
}

// 7. Repeat, while k < len
while (k < len) {
  // a. Let elementK be the result of ? Get(O, ! ToString(k)).
  // b. If SameValueZero(valueToFind, elementK) is true, return true.
  if (sameValueZero(o[k], valueToFind)) {
      return true;
  }
  // c. Increase k by 1. 
  k++;
}

因此,当您使用===比较两个不同的对象文字时,它们将不相等:

console.log({name :"John"} === {name :"John"});

但是另一方面,如果你将它们与===进行比较,原始字符串是相等的:

console.log('{name:"John"}' === '{name:"John"}');

但是String对象也是如此:

console.log(new String('{name:"John"}') === new String('{name:"John"}'));
© www.soinside.com 2019 - 2024. All rights reserved.