How to selectively insert keys to an object inside an array of objects based on condition like whether the value array is empty or not in Node.js

Tags: , ,



Here is the sample code block where I am inserting an object to an array of object through push method :

let sent_by;
let timestamp;
let txt;
let all_links = [];
let all_images = [];

data_object['messages'].push({
'sent_by' : sent_by,
'timestamp' : timestamp,
'content' : txt,
'links' : all_links,
'images' : all_images
})

How can I stop inserting the keys – content (string) , links (array) or images (array) to the array of objects when they are empty effectively in Node.js.

Answer

You can use the spread operator to conditionally add an element:

data_object["messages"].push({
  sent_by: sent_by,
  timestamp: timestamp,
  ...(txt && { content: txt }),
  ...(all_links.length > 0 && { links: all_links }),
  ...(all_images.length > 0 && { images: all_images })
});


Source: stackoverflow