Reputation: 397
I need to set an empty object as a default value if the array I'm passing in is empty. Something like:
var obj = { documents: [...question.documents] || [{}] }
I fixed it using a condition, but I want to know if there is a better way to achieve that.
if(obj.documents.length === 0) obj.documents.push({})
Upvotes: 4
Views: 2157
Reputation: 557
The shortest way
const obj1 ={...(true&& {x:1})};
console.log(obj1)
const obj2 ={...(false&& {y:1})};
console.log(obj2)
Upvotes: 0
Reputation: 14189
this should suit...
const question = {
documents: [],
};
const obj = {
documents: [].concat(question.documents.length ? question.documents : {})
};
console.log(obj);
Upvotes: 0
Reputation: 4553
The spread operator is used inside an empty array. I don't see the point in using the spread operator here. The objective can be achieved by using the following.
var obj = { documents: question.documents.length ? question.documents : [{}]}
If the method you have provided is being used, you don't need an or
clause, because an empty array also returns a truthy value. So it can be written as the following :-
var obj = { documents: question.documents }
if(!obj.documents.length) obj.documents.push({})
Upvotes: 1
Reputation: 31833
There are a couple of ways to write this in a single expression
Using the ternary operator:
var obj = { documents: [
...question.documents.length
? question.documents
: [{}]
]
};
Using a default value
var obj = { documents: [question.documents[0] || {}, ...question.documents.slice(1)] };
In both cases there's some awkwardness stemming from having to refer to the source multiple times
Upvotes: 1
Reputation: 370859
Since even empty arrays are truthy, I don't think there's any great elegant solution other than putting an explicit test in there somewhere. Ternaries are more terse than if
statements, though:
const question = { documents: [] };
const { documents } = question;
const obj = { documents: documents.length !== 0 ? documents : [{}]}
console.log(JSON.stringify(obj));
Here's another possibility:
const question = { documents: [] };
const [firstElm = {}, ...otherElms] = question.documents;
const obj = { documents: [firstElm, ...otherElms] };
console.log(obj);
Upvotes: 1