JavaScript中能否对getOplogStreamInterpreter返回对象进行多层解构?
Nested Object Destructuring for Direct Property Access
Absolutely! You’re totally on the right track—nested object destructuring is exactly the way to go here to skip the intermediate ops variable and grab insert, del, and update directly.
Original Approach
Your initial code first extracts the ops object, then accesses its properties one by one:
const {ops} = getOplogStreamInterpreter(strm); ops.del.subscribe(v => { console.log('delete happened 1.'); }); ops.insert.subscribe(v => { console.log('insert happened 1.'); }); ops.update.subscribe(v => { console.log('update happened 1.'); });
Optimized Nested Destructuring
The syntax you proposed is correct! You can destructure nested properties in one step like this:
const {ops: {insert, del, update}} = getOplogStreamInterpreter(strm);
This tells JavaScript:
- Take the object returned by
getOplogStreamInterpreter(strm) - Look for its
opsproperty - Extract the
insert,del, andupdateproperties fromopsand make them standalone variables in your current scope
Using the Destructured Variables
Now you can use these variables directly without referencing ops at all:
del.subscribe(v => { console.log('delete happened 1.'); }); insert.subscribe(v => { console.log('insert happened 1.'); }); update.subscribe(v => { console.log('update happened 1.'); });
This keeps your code cleaner and eliminates unnecessary intermediate variables—great call using this pattern!
内容的提问来源于stack exchange,提问作者Alexander Mills
相关产品推荐
相关产品推荐

