如何使用基于字符串值的排列运算符有条件地将对象插入数组



我有一个foobar对象,它们都有id道具:

{ id: fooId, name: 'John' }
{ id: barId, name: 'Jane' }

我想创建这些对象的数组arr,但仅在id不为空的情况下将对象插入到arr。我已经尝试过了,但它在我的数组中留下了一个空对象:

const fooId = '';
const barId = '2021';
const arr = [
...[(fooId ? {id: fooId, name: 'John'} : {})],
...[(barId ? {id: barId, name: 'Jane'} : {})],
];
console.log(arr.length);

在这种情况下,我想要arr.length === 1

返回一个带有对象的数组,如果id为空,则返回一个空数组,并将其展开。

const fooId = '';
const barId = '2021';
const arr = [
...fooId ? [{id: fooId, name: 'John'}] : [],
...barId ? [{id: barId, name: 'Jane'}] : [],
];
console.log(arr.length);

然而,将对象添加到数组中,然后在id为空时将其过滤掉会更容易、更干净:

const fooId = '';
const barId = '2021';
const arr = [
{id: fooId, name: 'John'},
{id: barId, name: 'Jane'},
].filter(o => o.id);
console.log(arr.length);

开始:

const fooId = '';
const barId = '2021';
const arr = [
...fooId && [{ id: fooId, name: 'John' }],
...barId && [{ id: barId, name: 'Jane' }],
];
console.log(arr);

或者像这个:

const fooId = '';
const barId = '2021';
const arr = [
fooId && { id: fooId, name: 'John' },
barId && { id: barId, name: 'Jane' },
].filter(Boolean);
console.log(arr);

最新更新