admin管理员组

文章数量:1313613

Is it possible to destructure only the values I need and not all of them:

 let {myVar, _ , lastVar} = {first:"I need this", second: "Not this", third:"I also need this"}

Is it possible to destructure only the values I need and not all of them:

 let {myVar, _ , lastVar} = {first:"I need this", second: "Not this", third:"I also need this"}
Share Improve this question edited Aug 2, 2017 at 15:40 CommonSenseCode asked Aug 2, 2017 at 15:36 CommonSenseCodeCommonSenseCode 25.4k38 gold badges148 silver badges195 bronze badges 2
  • 1 Documentation for this can be found here: developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – Zac Commented Aug 2, 2017 at 15:45
  • Your object has neither myVar nor lastVar properties. Are you confusing objects with arrays? – Bergi Commented Aug 2, 2017 at 17:55
Add a ment  | 

3 Answers 3

Reset to default 4

Yes of course.

If you have an object such as: {foo: 4, bar: 2}, and only foo is required:

let { foo } = {foo: 4, bar: 2};

This would also work:

let {first: first, third: third} = {first:"I need this", second: "Not this", third:"I also need this"}

You can easily rename destructured fields:

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)}`);

Yes,

let { a } = { a: 'a', b: 'b', c: 'c' }
// a is 'a'

or

let { a, ...rest } = {a: 'a', b: 'b'., c: 'c' }
// a is 'a'
// rest is { b: 'b', c: 'c' }

[edit - with your values]

let {first, third} = {first:"I need this", second: "Not this", third:"I also need this"}
// if you really want to change the variable names
let myVar = first, lastVar = third

本文标签: javascriptJS Destructuring some variables but not others on js or partial destructuringStack Overflow