I have two arrays with objects.
In the second object are the IDs of some objects from the first array.
Now I would like, if the ID of the object from the first array is found in the second, the object gets a new property with the name "hasinsurance" and the value "true".
var cars = [{id: 1, brand: "VW"},{id: 2, brand: "BMW"}];
var insurances = [{insurance: 'Allianz', car_id: 1}, {insurance: 'DKV', car_id: 3}];
I have already tried the following for this purpose:
cars.filter((item) => {
insurances.filter((item2) => {
if (item.id === item2.car_id)
item. hasinsurance = true
else
item. hasinsurance = false
})
})
Unfortunately, it is then that all get the entry false, and I can not find the error.
4
Answers
filter is going to keep looping after you find the car that matches. The only way you are going to get true is if the LAST insurance index is the item. You need to use some and you should not be using filter to loop.
Most people would not use some, but would do a mapping with either an object or Map and do a look up.
The callback passed to Array.prototype.filter should return a boolean value. I do not see where is your return in the example.
if I understood your problem correctly, you could consider trying something like the following:
I hope this is helpful.
You can use Array.map and Array.some to add new property add and check id in second array.
Example: