An Interest In:
Web News this Week
- March 20, 2024
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
- March 15, 2024
- March 14, 2024
June 11, 2022 10:11 am GMT
Original Link: https://dev.to/jacksonkasi/array-of-object-manipulation-in-javascript-6bd
Array of Object Manipulation in JavaScript
how to get the difference between two arrays of objects and merge in a single object?
two array of objects
const befor = [ { one: "123", two: "124", three: "127", },];const after = [ { one: "123", two: "125", three: "128", },];
let newChanges = Object.keys(befor[0]).map( (item) => befor[0][item] !== after[0][item] && { [item]: after[0][item] });console.log(newChanges)
output:
We do not need the **boolean **value here.
Don't worry about it.
I will tell you about this later.
let result = Object.assign({}, ...newChanges);console.log(result)
now output:
{ two: '125', four: '130' }
WHF?
Object.assign( ) create an Object.
This requires key and value.
But Boolean value is a value of one.
Therefore Object.assign( ) does not recognize the boolean value
But I can not say this is the right reason
another solution
newChanges = newChanges.filter(Boolean)console.log(newChanges);
what happen?
The filter method filters out all the values that return false when passed to a function.
When you use filter and pass a Boolean constructor.
full Code here :
const befor = [ { one: "123", two: "124", three: "128", four: "132", },];const after = [ { one: "123", two: "125", three: "128", four: "130", },];let newChanges = Object.keys(befor[0]).map( (item) => befor[0][item] !== after[0][item] && { [item]: after[0][item] });newChanges = newChanges.filter(Boolean)// console.log(newChanges);let result = Object.assign({}, ...newChanges);console.log(result);
result :
{ two: '125', four: '130' }
conclusion
Just wanted to share this with you
If you find another great way to do this don't forget to share here.
Original Link: https://dev.to/jacksonkasi/array-of-object-manipulation-in-javascript-6bd
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To