我想编写一个表达式,它采用 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/