简体   繁体   English

如何根据条件(例如 Node.js 中的值数组是否为空)有选择地向对象数组中的对象插入键

[英]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

Here is the sample code block where I am inserting an object to an array of object through push method :这是我通过 push 方法将对象插入到对象数组的示例代码块:

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.当它们在 Node.js 中有效为空时,如何停止将键 - 内容(字符串)、链接(数组)或图像(数组)插入到对象数组中。

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 })
});

Use a simple if statement in your control structure:在您的控制结构中使用简单的if语句:

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只有那些拥有 3 个道具的元素才会被推送到数组中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM