javascript - ES6 : Conditional use of spread operator

标签 javascript ecmascript-6

我想编写一个表达式,它采用 query 参数的值并生成一个新对象,其中包含 query 中的所有内容和默认的 $sort 值,但前提是 $sort 不存在。

我觉得我应该使用扩展运算符 ... 来执行此操作,但不知道在这种情况下如何使用它。

下面的代码不起作用,因为它总是返回 {$sort: {priority: -1, createdAt: -1}} 理想情况下,它应该打印出 console.log 语句旁边注释中的内容:

'use strict'
const funcUnderTest = (query) => ({
  query: /^sort/.test(query) ? query : {$sort: {priority: -1, createdAt: -1}}
})

console.log(funcUnderTest(null)) // Should be { query: {$sort: {priority: -1, createdAt: -1}}}
console.log(funcUnderTest(({}))) // Should be { query: {$sort: {priority: -1, createdAt: -1}}}
console.log(funcUnderTest(({forCandidate: 123}))) // Should be { query: {forCandidate: 123, $sort: {priority: -1, createdAt: -1}}}
console.log(funcUnderTest(({$sort: {name:1}}))) // Should be { query: {$sort: {name: 1}}}
console.log(funcUnderTest(({forCandidate: 123, $sort: {name:1}}))) // Should be { forCandidate: 123, query: {$sort: {name: 1}}}

最佳答案

您可以为此使用Object.assign

我假设你的最后一个示例输出是错误的(应该是 { query: {$sort: {name: 1}, forCandidate: 123}})因为它与你的不一致其他预期产出。

'use strict'
const funcUnderTest = (query) => ({
  query: Object.assign({$sort: {priority: -1, createdAt: -1}}, query || {})
})

console.log(funcUnderTest(null)) // Should be { query: {$sort: {priority: -1, createdAt: -1}}}
console.log(funcUnderTest(({}))) // Should be { query: {$sort: {priority: -1, createdAt: -1}}}
console.log(funcUnderTest(({forCandidate: 123}))) // Should be { query: {forCandidate: 123, $sort: {priority: -1, createdAt: -1}}}
console.log(funcUnderTest(({$sort: {name:1}}))) // Should be { query: {$sort: {name: 1}}}
console.log(funcUnderTest(({forCandidate: 123, $sort: {name:1}}))) // Should be { forCandidate: 123, query: {$sort: {name: 1}}}

关于javascript - ES6 : Conditional use of spread operator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45717922/

相关文章:

javascript - 从 javascript 触发 actionscript 函数(在 flash 对象中)

javascript - 无法将元素的设置值设置为 "innerHTML"

javascript - 当 ob1.prototype 未定义时,Object.create() 如何从 ob1.prototype 创建 obj2.__proto__ ?

javascript - 检测 ES6 类中的静态超方法

javascript - 语法错误: Unexpected reserved word 'export' in meteor package

javascript - gulp userref 从管道中删除文件

javascript - 有人可以帮我自动播放 slider 吗?

javascript - JSON 将数字解析为字符串

javascript - 通过 id 从列表中检索多个项目

javascript - 使用数组内的对象进行解构赋值