0

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.

2 Answers 2

2

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 })
});
Sign up to request clarification or add additional context in comments.

Comments

0

Use a simple if statement in your control structure:

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

Only those elements who have the 3 props, will be pushed to the array

2 Comments

There could be other conditions like txt is present but others are not present or any one of them is present.
Ok I got it, I missunderstood you. If thats the case, the other answer could be helpful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.