如何在javascript中合并两个可选数组

时间:2022-10-04 12:13:40

How would you merge two optional arrays in Javascript these days? This is the best I got so far:

如何在Javascript中合并两个可选数组?这是我到目前为止最好的:

const trades = this.position.trades; // trades or maintenance can be undefined
const maintenance = this.position.maintenance;
const principals = [... trades ? trades : [], ... maintenance ? maintenance : []];

Looking for elegant solutions while dealing with the fact that either array can be undefined (aka optional). Thanks!

寻找优雅的解决方案,同时处理任何数组都可以未定义的事实(也称为可选)。谢谢!

PS: I'm using Typescript 2.6 / ES6

PS:我正在使用Typescript 2.6 / ES6

2 个解决方案

#1


5  

You can do something like this. || this will return [] if the first operand is falsy.

你可以做这样的事情。 ||如果第一个操作数是假的,这将返回[]。

const trades = this.position.trades || []; 
const maintenance = this.position.maintenance || [];
const principals = [...trades, ...maintenance];

Or instead of the spread operator just use Array#concat

或者代替扩展运算符只使用Array#concat

const trades = this.position.trades || []; 
const maintenance = this.position.maintenance || [];
const principals = trades.concat(maintenance);

#2


2  

You can use the || operator in conjunction with the spread operator which you already use:

你可以使用||运算符与您已使用的扩展运算符一起使用:

const principals = [...this.position.trades || [], ...this.position.maintenance || []];

#1


5  

You can do something like this. || this will return [] if the first operand is falsy.

你可以做这样的事情。 ||如果第一个操作数是假的,这将返回[]。

const trades = this.position.trades || []; 
const maintenance = this.position.maintenance || [];
const principals = [...trades, ...maintenance];

Or instead of the spread operator just use Array#concat

或者代替扩展运算符只使用Array#concat

const trades = this.position.trades || []; 
const maintenance = this.position.maintenance || [];
const principals = trades.concat(maintenance);

#2


2  

You can use the || operator in conjunction with the spread operator which you already use:

你可以使用||运算符与您已使用的扩展运算符一起使用:

const principals = [...this.position.trades || [], ...this.position.maintenance || []];