Let’s say there is an object that looks like this:
const object = { cars: { car1: { model: "Car 1 model", name: "Car 1 name", // <-- export this }, car2: { model: "Car 2 model", name: "Car 2 name", // <-- export this }, }, bikes: { bike1: { model: "Bike 1 model", name: "Bike 1 name", // <-- export this }, bike2: { model: "Bike 2 model", name: "Bike 2 name", // <-- export this }, }, };
Now I would like to export some of the nested values so that it can be used in various files across the app (exporting the entire object is not an option). What we could do is manually create all the required variables and export them like this:
export const car1Name = object.cars.car1.name; export const car2Name = object.cars.car2.name; export const bike1Name = object.bikes.bike1.name; export const bike2Name = object.bikes.bike2.name;
The problem is that if we add more properties to this object (more cars or bikes), it will be very difficult to maintain as we have to manually create new variable and export them each time something new is added. Could you advice how this can be improved?
Advertisement
Answer
I suppose you could iterate through the object, construct a similar key for each vehicle/model, then export another object or array with that data.
const object = { cars: { car1: { model: "Car 1 model", name: "Car 1 name", // <-- export this }, car2: { model: "Car 2 model", name: "Car 2 name", // <-- export this }, }, bikes: { bike1: { model: "Bike 1 model", name: "Bike 1 name", // <-- export this }, bike2: { model: "Bike 2 model", name: "Bike 2 name", // <-- export this }, }, }; const modelNames = Object.fromEntries( Object.values(object).flatMap(vehicles => ( Object.entries(vehicles).map(([key, { name }]) => [key, name]) )) ); console.log(modelNames);
or
const object = { cars: { car1: { model: "Car 1 model", name: "Car 1 name", // <-- export this }, car2: { model: "Car 2 model", name: "Car 2 name", // <-- export this }, }, bikes: { bike1: { model: "Bike 1 model", name: "Bike 1 name", // <-- export this }, bike2: { model: "Bike 2 model", name: "Bike 2 name", // <-- export this }, }, }; const modelNames = Object.fromEntries( Object.entries(object).flatMap(([vehicleType, vehicles]) => ( Object.entries(vehicles).map(([key, { name }]) => [vehicleType + '_' + key, name]) )) ); console.log(modelNames);
or
const object = { cars: { car1: { model: "Car 1 model", name: "Car 1 name", // <-- export this }, car2: { model: "Car 2 model", name: "Car 2 name", // <-- export this }, }, bikes: { bike1: { model: "Bike 1 model", name: "Bike 1 name", // <-- export this }, bike2: { model: "Bike 2 model", name: "Bike 2 name", // <-- export this }, }, }; const modelNames = JSON.parse(JSON.stringify( object, (key, value) => 'name' in value ? value.name : value )); console.log(modelNames);