skip to Main Content

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


  1. 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];
    });
    
    Login or Signup to reply.
  2. The callback passed to Array.prototype.filter should return a boolean value. I do not see where is your return in the example.

    Login or Signup to reply.
  3. if I understood your problem correctly, you could consider trying something like the following:

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

    I hope this is helpful.

    Login or Signup to reply.
  4. You can use Array.map and Array.some to add new property add and check id in second array.

    Example:

        cars = cars.map(car=> {
        return {
            ...car,
            hasInsurance: insurances.some(({ car_id }) => car.id === car_id)
             }
       });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search