I have a foo
and a bar
object that both have an id
prop:
{ id: fooId, name: 'John' }
{ id: barId, name: 'Jane' }
I want to create an array arr
of these objects but only insert the object to the arr
if the id
is not empty. I've tried this, but it leaves an empty object inside my array:
const fooId = ''; const barId = '2021'; const arr = [...[(fooId? {id: fooId, name: 'John'}: {})], ...[(barId? {id: barId, name: 'Jane'}: {})], ]; console.log(arr.length);
And I want arr.length === 1
in this case.
Return an array with an object, or an empty array if the id is empty, and spread it.
const fooId = ''; const barId = '2021'; const arr = [...fooId? [{id: fooId, name: 'John'}]: [], ...barId? [{id: barId, name: 'Jane'}]: [], ]; console.log(arr.length);
However, it's easier and cleaner to add the objects to the array, and then filter them out if the id
is empty:
const fooId = ''; const barId = '2021'; const arr = [ {id: fooId, name: 'John'}, {id: barId, name: 'Jane'}, ].filter(o => o.id); console.log(arr.length);
Here you go:
const fooId = ''; const barId = '2021'; const arr = [...fooId && [{ id: fooId, name: 'John' }], ...barId && [{ id: barId, name: 'Jane' }], ]; console.log(arr);
Or like this one:
const fooId = ''; const barId = '2021'; const arr = [ fooId && { id: fooId, name: 'John' }, barId && { id: barId, name: 'Jane' }, ].filter(Boolean); console.log(arr);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.