Boky Boky - 3 months ago 8
Javascript Question

Filter through an array in javascript

I have one array with a list of all cars, as follows :

const allCars = [
{id: 1, listID: 1, name: "Car 1", chassis: "000000000"},
{id: 2, listID: 2, name: "Car 2", chassis: "111111111"},
{id: 3, listID: 1, name: "Car 3", chassis: "222222222"},
{id: 4, listID: 1, name: "Car 4", chassis: "333333333"}
];


and I have some of those cars in the shopping cart, as follows :

const carsInCart = [
{carID: 1, listID: 1, offer: 488},
{carID: 2, listID: 2, offer: 786},
]


Is there any way to filter throught allCars and return only those which are in carsInCart, and return only chassis from allCars and offer from carsInCart?

Thus, what I want is something like this :

const result = [
{chassis: 000000000, offer: 488},
{chassis: 111111111, offer: 786}
]

hsz hsz
Answer

Just try with:

const result = carsInCart.map(function (car) {
  const aCar = allCars.find(function (c) {
    return c.id === car.ID;
  });
  return { chassis: aCar.chassis, offer: car.offer };
});

Or with functions shorthands:

const result = carsInCart.map(car => {
  chassis: allCars.find(c => c.id === car.ID).chassis,
  offer:   car.offer
});
Comments