1

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)?

redOctober13
  • 3,662
  • 6
  • 34
  • 61

2 Answers2

2

This should work:

({ cars, trucks } = carsAndTrucks)

PLs see this answer as well

How to destructure an object to an already defined variable?

R Claven
  • 1,160
  • 2
  • 13
  • 27
1

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.

zlumer
  • 6,844
  • 1
  • 25
  • 25