Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add new key/value to Object in an Array when id is found in second array with objects

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

cars.forEach((car) => {
    const id = car.id
    car.hasInsurance = insurances.some(({ car_id }) => id === car_id);
});

Most people would not use some, but would do a mapping with either an object or Map and do a look up.


const insuranceByCar = insurances.reduce((acc, policy) => {
  acc[policy.car_id] = policy;
}, {});

cars.forEach((car) => {
    car.hasInsurance = !!insuranceByCar[car.id];
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading