0

Trying to get the filtered array based on the selected object. How can I loop through damaged array which is inside the object and get the resultant array? I tried to add another condition using .map but it prints the rest of the items as well.

Below is the snippet

const inventory = [{
  name: 'Jeep',
  id: '100',
  damaged: [{
      name: 'Wrangler',
      id: '200'
    },
    {
      name: 'Sahara',
      id: '201'
    }
  ]
}, {
  name: 'Audi',
  id: '101',
  damaged: [{
    name: 'Q3',
    id: '300'
  }]
}]

const purchasedCars = [{
    car: 'Jeep',
    id: '100'
  }, {
    car: 'Jeep - Wrangler',
    id: '200',
  },
  {
    car: 'Jeep - Sahara',
    id: '201'
  },
  {
    car: 'Audi - Q3',
    id: '300'
  }
]

const selectedCar = purchasedCars[0];

const filterCars = () => {
  const result = purchasedCars.filter((inv) => inv.id === selectedCar.id)
  console.log('result -->', result);
}

filterCars();

Expected output is

[{
    car: 'Jeep',
    id: '100'
  }, 
 {
    car: 'Jeep - Wrangler',
    id: '200',
  },
  {
    car: 'Jeep - Sahara',
    id: '201'
}]

Could anyone please help?

2
  • Please elaborate on what you are trying to do. Why is that the expected output? Commented Jan 25, 2023 at 19:20
  • you are not using the inventory array in your code. Can you try to explain what you are trying to do a bit more clearly? Commented Jan 25, 2023 at 19:21

1 Answer 1

1

Trying to read your mind here. Is this what you want?

const inventory = [{
  name: 'Jeep',
  id: '100',
  damaged: [{
      name: 'Wrangler',
      id: '200'
    },
    {
      name: 'Sahara',
      id: '201'
    }
  ]
}, {
  name: 'Audi',
  id: '101',
  damaged: [{
    name: 'Q3',
    id: '300'
  }]
}]

const purchasedCars = [{
    car: 'Jeep',
    id: '100'
  }, {
    car: 'Jeep - Wrangler',
    id: '200',
  },
  {
    car: 'Jeep - Sahara',
    id: '201'
  },
  {
    car: 'Audi - Q3',
    id: '300'
  }
]

const selectedCar = purchasedCars[0];

const filterCars = () => {
  let result;
  const parentItem = inventory.filter((inv) => inv.id === selectedCar.id)[0];
  
  if ("damaged" in parentItem) {
      result = [selectedCar, ...(parentItem.damaged)];
  }
  
  console.log('result -->', result);
}

filterCars();

Note that if you can have more nested car types in the damaged property you would you to call filterCars recursively and pass in the car object. If you also want to filters items that may also be present in the damaged property, then you would first need to use the flatMap method (before the filter).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.