码迷,mamicode.com
首页 > 编程语言 > 详细

[Javascript] Conditionally spread entries to a JavaScript object

时间:2019-01-16 16:37:44      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:http   less   web   col   HERE   org   cer   userdata   several   

In JavaScript, we often end up composing one object out of several other objects. Luckily there‘s a convenient spread operator which allows us to spread entries from one object to another.

Sometimes we only want to include something in the newly created object if a certain condition is met. In this lesson we are going to learn how to conditionally add entries to a JavaScript object using the spread operator.

 

const isAdmin = () => true;

const userData = {
  name: "Tomasz",
  surname: "?akomy"
};

// TODO:
// if user is an admin, add a is_admin: true
// to the object, otherwise don‘t add anything
const userObject = {
  id: 123,
  ...userData,
  ...(isAdmin() ? { is_admin: true } : {})
};

console.log(userObject);

 

[Javascript] Conditionally spread entries to a JavaScript object

标签:http   less   web   col   HERE   org   cer   userdata   several   

原文地址:https://www.cnblogs.com/Answer1215/p/10277428.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!