最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is it possible to destructure to already-declared variables? - Stack Overflow

programmeradmin3浏览0评论

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 has cars and trucks, 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
Add a ment  | 

2 Answers 2

Reset to default 8

This 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.

发布评论

评论列表(0)

  1. 暂无评论