2

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
  • 756,363
  • 169
  • 1,062
  • 1,111
levis
  • 337
  • 7
  • 16
  • 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

4 Answers4

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
  • 313,535
  • 40
  • 245
  • 254
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
  • 26,341
  • 6
  • 64
  • 77
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
  • 3,872
  • 2
  • 25
  • 43
0

this should suit...

const question = {
  documents: [],
};

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

console.log(obj);
Hitmands
  • 12,577
  • 3
  • 30
  • 62