#Referencing an object from another array

12 messages · Page 1 of 1 (latest)

heady basalt
#

I have two arrays of objects in my code, one is holding form data, the other is holding additional info used to spruce up the form. While looping over my form data, I get the relevant object like this:

type fields = {car_id: number; // ...}[];
type cars = {car_id: number; //... }[];
fields.map((field) => {
  const car = cars.find((car) => car.car_id === field.car_id); // car might be undefined while in reality it never is
  // do something with car
});

Is there a way to handle this in typescript so it knows a car will always be found?

blissful salmon
#

could you restructure things to make cars be an object keyed by ID rather than an array?

#

that'd be faster too (O(1) lookup rather than having to search the whole cars array for each field)

heady basalt
#

absolutely. but isn't that the same problem then, that it might think object[car_id] is undefined?

blissful salmon
#

not if it's defined statically:

oak spearBOT
#
mkantor#0

Preview:```ts
type fields = {car_id: 123 /.../}[]
type cars = {
123: {
/.../
}
}

declare const fields: fields
declare const cars: cars

fields.map(field => {
const car = cars[field.car_id]
// do something with car
})```

blissful salmon
#

that was going to be my next question: how are fields and cars populated?

#

(BTW typically type names are Uppercase and values are lowercase. i kept getting confused working in that playground)

heady basalt
#

cars is loaded dynamically from the backend, fields is a map from cars.

blissful salmon
#

ah then yes you might not be able to guarantee that cars[car_id] exists with this setup

#

fields is a map from cars
can you show me roughly how this part works? you might be able to do something here to tie things together

heady basalt
#

@blissful salmon

useEffect(() => {
    http.post('/quotes/cars', {
            car_ids: carIds,
        })
        .then((response) => {
            setCars({response.data});
        });
}, []);

return (
  <Form
    defaultValues={{
        // other fields
        lines: cars.cars.map((car) => ({
            type: 'CAR',
            car_id: car.car_id,
            base_pricing: 'WEBSITE_PRICING_BE',
            price: car.price_BE,
        })),
    }}
  >
     // 
  </Form>
)