javascript - JS Destrukturering av vissa variabler men inte andra i js eller partiell destrukturering
Är det möjligt att destrukturera endast de värden jag behöver och inte alla:
let {myVar, _ , lastVar} = {first:"I need this", second: "Not this", third:"I also need this"}
Svar #1
Ja, självklart.
Om du har ett objekt såsom: {foo: 4, bar: 2}, och endast foo är obligatoriskt:
let { foo } = {foo: 4, bar: 2};
Detta skulle också fungera:
let {first: first, third: third} = {first:"I need this", second: "Not this", third:"I also need this"}
Svar #2
Du kan enkelt byta namn på destrukturerade fält:
const o = {
first:"I need this",
second: "Not this",
third:"I also need this"};
const {first: myVar, third: lastVar, ...rest} = o;
//
console.log(` myVar - ${myVar}`);
console.log(`lastVar - ${lastVar}`);
console.log(` rest - ${JSON.stringify(rest)}`);
