[Javascript] Conditionally spread entries to a JavaScript object

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Javascript] Conditionally spread entries to a JavaScript object相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

javascript的题。

javascript JavaScript isset()等效: - JavaScript

JavaScript 使用JavaScript更改CSS(JavaScript)

JavaScript之基础-1 JavaScript(概述基础语法)

前端基础-JavaScript的基本概述和语法

JavaScript