The following TypeScript works:
const carsAndTrucks = { cars: [], trucks: [] };
const { cars, trucks } = mapDealerInventory();
carsAndTrucks.cars = cars
carsAndTrucks.trucks = trucks
console.log(carsAndTrucks)
function mapDealerInventory() {
return {cars: [1,2], trucks:['a', 'b']}
}
But is there a way to avoid having to set new variables just to destructure the return value of mapDealerInventory()
? I was hoping this was possible:
{ carsAndTrucks.cars, carsAndTrucks.trucks } = mapDealerInventory()
but it gives the error "Unexpected token ="
So if you declare an object with its property types first, what's the cleanest way to set those properties from a function that returns their values in an object (or an array)?
The following TypeScript works:
const carsAndTrucks = { cars: [], trucks: [] };
const { cars, trucks } = mapDealerInventory();
carsAndTrucks.cars = cars
carsAndTrucks.trucks = trucks
console.log(carsAndTrucks)
function mapDealerInventory() {
return {cars: [1,2], trucks:['a', 'b']}
}
But is there a way to avoid having to set new variables just to destructure the return value of mapDealerInventory()
? I was hoping this was possible:
{ carsAndTrucks.cars, carsAndTrucks.trucks } = mapDealerInventory()
but it gives the error "Unexpected token ="
So if you declare an object with its property types first, what's the cleanest way to set those properties from a function that returns their values in an object (or an array)?
Share Improve this question asked Jun 25, 2018 at 10:24 redOctober13redOctober13 4,0246 gold badges40 silver badges66 bronze badges 3-
3
If
carsAndTrucks
only hascars
andtrucks
, why destructure at all? Might be easier to just reassign – CertainPerformance Commented Jun 25, 2018 at 10:25 -
Object.assign(carsAndTrucks, mapDealerInventory())
– Keith Commented Jun 25, 2018 at 10:28 - Well, I simplified a bit. In this case, carsAndTrucks actually has more properties than just those two. – redOctober13 Commented Jun 25, 2018 at 11:21
2 Answers
Reset to default 8This should work:
({ cars, trucks } = carsAndTrucks)
PLs see this answer as well
How to destructure an object to an already defined variable?
Use Object.assign() to set multiple fields on an object:
const { cars, trucks } = mapDealerInventory();
Object.assign(carsAndTrucks, { cars, trucks });
Or, if you don't need cars
and trucks
variables for anything else and mapDealerInventory()
returns only these two fields:
Object.assign(carsAndTrucks, mapDealerInventory());
carsAndTrucks
will retain all other properties, and cars
and trucks
will be changed.