简体   繁体   中英

ES6: Conditional use of spread operator

I would like to write an expression which takes the value of the query parameter and generates a new object which contains everything in query and the default $sort value, but only if $sort is not already present.

I feel like I should use the the spread operator ... to do this, but don't know how I could use it in this instance.

The below code does not work as it always returns {$sort: {priority: -1, createdAt: -1}} Ideally it should print out what's in the comments next to the console.log statements:

'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}}}

You can use Object.assign for this.

I'm going to assume your last example output is a mistake (should be { query: {$sort: {name: 1}, forCandidate: 123}} ) because it's inconsistent with your other expected outputs.

 '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}}} 

Thanks to @JLRishe 's answer, and understanding that Object.assign is the same as using spread syntax except that since it's non-mutative there is no need for the {} after the || , here is the version with spread syntax.

 'use strict' const funcUnderTest = (query) => ({ query: { $sort: {priority: -1, createdAt: -1}, ...query } }) console.log(funcUnderTest(null)) console.log(funcUnderTest(({}))) console.log(funcUnderTest(({forCandidate: 123}))) console.log(funcUnderTest(({$sort: {name:1}}))) console.log(funcUnderTest(({forCandidate: 123, $sort: {name:1}}))) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM