I have two arrays of objects. Each object will have a unique property id which, for context, is a filterID retrieved from a dynamoDb database. What I want to achieve is, retrieving an array of the objects that are different given the same id.
const x = [
{
1234: "food"
},
{
5678: "animal"
},
{
4444: "car"
}
]
const y = [
{
1234: "food"
},
{
5678: "bread"
},
{
4444: "car"
}
]
const p = () => x.filter(object1 => {
return !y.some(object2 => {
return object1 === object2
})
})
console.log(p())
In this scenario I would be looking for something like
const different = [
{
5678: "animal"
},
]
I have tried a few things like on the example above but so far no success.
CodePudding user response:
You're close, you just need to get the object key and compare the values, instead of comparing the object references.
const p = () => x.filter(object1 => {
return !y.some(object2 => {
const key = Object.keys(object1)[0];
return object1[key] == object2[key];
})
})
console.log(p())
CodePudding user response:
use this code instead:
const p = () =>
x.filter((object1) => {
return !y.some((object2) => {
return JSON.stringify(object1) === JSON.stringify(object2);
});
});
console.log(p());
you cannot compare two objects because they always will be different because they are at different location in memory, you have to compare their properties or convert them to string and compare them