I have the following two object arrays. I would like to update array1 elements to reflect array2 elements where the transid matches. So my result should be either a new array that has the two elements from array1 updated to reflect the values in array2, or the same array1 with the updated values.
What is the best way to do that with some of the more modern syntax? I open to several options so I can compare. For example, I'm guessing matching objects in array1 can just be replaced with array2 objects or the individual elements within the array1 objects can be updated through some sort of iteration over the elements.
var arra1 = [{
"_id" : ObjectId("583f6e6d14c8042dd7c979e6"),
"transid" : 1,
"acct" : "acct1",
"transdate" : ISODate("2012-01-31T05:00:00.000Z"),
"category" : "category1",
"amount" : 103
}, {
"_id" : ObjectId("583f6e6d14c8042dd7c2132t6"),
"transid" : 2,
"acct" : "acct2",
"transdate" : ISODate("2012-01-31T05:00:00.000Z"),
"category" : "category2",
"amount" : 103
}]
var arra2 = [{
"_id" : ObjectId("583f6e6d14c8042dd7c979e6"),
"transid" : 1,
"acct" : "acct2",
"transdate" : ISODate("2012-01-31T05:00:00.000Z"),
"category" : "category5",
"amount" : 107
}, {
"_id" : ObjectId("583f6e6d14c8042dd7c2132t6"),
"transid" : 2,
"acct" : "acct2",
"transdate" : ISODate("2012-01-31T05:00:00.000Z"),
"category" : "category2",
"amount" : 103
}, {
"_id" : ObjectId("583f6e6d14c8042dd7c2132t6"),
"transid" : 3,
"acct" : "acct2",
"transdate" : ISODate("2016-07-31T05:00:00.000Z"),
"category" : "category3",
"amount" : 103
}]
I played with it a bit and have something like this thus far. It's not working but that's the type of logic I'm looking for.
arr1.forEach(item =>
if (arr2.indexOf(item.transid) != -1){
item.category = arr2.indexOf(item.transid).category
}
)
To change the value of an object in an array:Call the findIndex() method to get the index of the specific object. Access the array at the index and change the property's value using dot notation. The value of the object in the array will get updated in place.
To change the position of an element in an array:Use the splice() method to insert the element at the new index in the array. The splice method changes the original array by removing or replacing existing elements, or adding new elements at a specific index.
arra1 = arra1.map(item => {
const item2 = arra2.find(i2 => i2.transid === item.transid);
return item2 ? { ...item, ...item2 } : item;
});
Map all elements in arra1
into arra1
itself. On the mapping function try to find the correlative item in arra2
and merge the two items with object spread if its found, if not, return the original item. Notice that spreading item2
last is crucial to the merge, so you overwrite with the values from item2
but keep those in item1
that were not overwritten.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With