Skip to content
Advertisement

How to replace object props inside array with other object

I have an array of objects like this one:

JavaScript

I want to replace the status.code by the one given in this other array of objects:

JavaScript

My idea is to map the first array and the use the find function (or filter) to loop the second array and when the ID’s match change the values but I’m missing something, how can i do this the most optimized for performance and readability way?

JavaScript

Advertisement

Answer

I would first change the format of arr2 in such a way that it is easier to access in such a format: (If you can easily change how you get this data, it would be better I think. Otherwise, transform the data as below.)

JavaScript

We do this so we can just look if there is idStatusCodeMap[10] or idStatusCodeMap[anyId]. This makes it possible that you only loop through arr1, not a nested loop for both arr1 and arr2. Then, loop through arr1 and replace the colours if necessary. If suppose, a new colour is not found on idStatusCodeMap, such as for id = 30, then don’t do anything for that.

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement