[Javascript] Conditionally spread entries to a JavaScript object
JavaScript to object spread
2023-09-14 09:00:49 时间
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获取DOM节点
- 【阮一峰】深入研究URL编码问题及JavaScript相应的解决方案
- 【JavaScript 6连载】四、apply和call的用法
- [Javascript] Object.freeze: using Object.freeze in function params to enforce immutabtility
- [Javascript] Broadcaster + Operator + Listener pattern -- 10. Define a Function to Set Common Behaviors in Operators
- [Functional Programming] Draw Items from One JavaScript Array to Another using a Pair ADT
- [Javascript] Use a Pure RNG with the State ADT to Select an Element from State
- [Javascript] Immute Object
- [Javascript] Using console.count to Count Events
- [Javascript] Intro to Recursion
- [Javascript] Augmentation
- 编写javascript的基本技巧
- 一个JavaScript Function Outliner插件 第三个版本 让你的JavaScript代码也支持折叠
- [Javascript] Link to Other Objects through the JavaScript Prototype Chain (Object.setPrototypeOf())
- [Javascript] How to deal with floating number
- [Rust] Pass a JavaScript Function to WebAssembly and Invoke it from Rust
- [Poi] Use Poi to Build an Index.js with Modern JavaScript Features
- JavaScript操作Xml
- javascript document.write
- 如何使用原生的 JavaScript 代码,触发 SAP UI5 按钮控件的点击事件处理函数
- Jerry的ABAP, Java和JavaScript乱炖
- DHTMLX JavaScript 待办事项+To Do List