3

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({})
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
levis
  • 367
  • 7
  • 17
  • There is no such thing as a speed operator: https://stackoverflow.com/questions/37151966/what-is-spreadelement-in-ecmascript-documentation-is-it-the-same-as-spread-oper/37152508#37152508 – Felix Kling Apr 14 '18 at 14:59

5 Answers5

1

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);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

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

Aluan Haddad
  • 29,886
  • 8
  • 72
  • 84
1

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({})
Akash Dathan
  • 4,348
  • 2
  • 24
  • 45
0

this should suit...

const question = {
  documents: [],
};

const obj = { 
  documents: [].concat(question.documents.length ? question.documents : {}) 
};

console.log(obj);
Hitmands
  • 13,491
  • 4
  • 34
  • 69
0

The shortest way

const  obj1 ={...(true&& {x:1})};
console.log(obj1)
const  obj2 ={...(false&& {y:1})};
console.log(obj2)
Amr Omar
  • 399
  • 5
  • 12