There are couple of options to do that. The issue is with your code even if it looks like you are trying to check with indexOf
if the array contains the targeted object. The main issue is it does not check the values of the properties but the reference of the original object.
So the first solution is, checking each property of the object in a hard coded way if you have the same structure for your object:
const links = [
{x: '2', y: '3', z: '1'},
{x: '11', y: '32', z: '73'},
{x: '1', y: '2', z: '3'},
{x: '93', y: '6', z: '76'},
];
const aim = {x: '1', y: '2', z: '3'};
links.forEach(link => {
const result = link.x === aim.x && link.y === aim.y && link.z === aim.z;
console.log(link, `This object has same property values as aim: ${result}`);
});
There are smarter solutions, just like getting the keys
of the object what it has dynamically and comparing them by using some()
:
const links = [
{x: '2', y: '3', z: '1'},
{x: '11', y: '32', z: '73'},
{x: '1', y: '2', z: '3'},
{x: '93', y: '6', z: '76'},
];
const aim = {x: '1', y: '2', z: '3'};
links.forEach(link => {
const keysOfLink = Object.keys(link);
const keysOfAim = Object.keys(aim);
const result = keysOfLink.length === keysOfAim.length &&
keysOfLink.some(key => link[key] === aim[key]);
console.log(link, `This object has same property values as aim: ${result}`);
});
I would go with the second option, that's definitely smartest way to check.
From Array.prototype.some()
's documentation:
The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.
Once in the result
variable you have true
value, you can push
as you wanted originally.
I hope this helps!