Is it somehow possible to compare an array of objects based on a key? #39
Unanswered
mmailaender
asked this question in
Q&A
Replies: 1 comment
-
The best way to do this would be to convert it into an object and then diff it. e.g. const array1 = [
{
id: '1',
originalProperty: true
},
{
id: '2',
originalProperty: true
}
];
const array2 = [
{
id: '1',
originalProperty: true,
newProperty: true
},
{
id: '3',
originalProperty: true
}
];
function convert(array) {
const res = {};
for (let arrayEl of array) {
res[arrayEl.id] = arrayEl;
}
return res;
}
diff(convert(array1), convert(array2))
/*
[
{ type: "CREATE", path: [ "1", "newProperty" ], value: true },
{
type: "REMOVE",
path: [ "2" ],
oldValue: { id: "2", originalProperty: true }
},
{
type: "CREATE",
path: [ "3" ],
value: { id: "3", originalProperty: true }
}
]
*/ Does that work for your use case? I might have misinterpreted your question. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
e.g.:
Beta Was this translation helpful? Give feedback.
All reactions