admin管理员组

文章数量:1323707

What's the cleanest way to destructure the following object?

const e = {
  target: {
    userid: {
      value: 'abc'
    },
    password: {
      value: 'xyz'
    }
  }
}

The object is how an HTML form returns data and I'm trying to retrieve values using ONLY destructuring. My attempt was:

const {target: {userid: {value}, password: {value}}} = e;

But it chokes on the two values having the same property name. Any ES6 alternative?

What's the cleanest way to destructure the following object?

const e = {
  target: {
    userid: {
      value: 'abc'
    },
    password: {
      value: 'xyz'
    }
  }
}

The object is how an HTML form returns data and I'm trying to retrieve values using ONLY destructuring. My attempt was:

const {target: {userid: {value}, password: {value}}} = e;

But it chokes on the two values having the same property name. Any ES6 alternative?

Share Improve this question edited Aug 20, 2019 at 6:51 FZs 18.6k13 gold badges46 silver badges56 bronze badges asked Aug 20, 2019 at 6:44 TheLearnerTheLearner 2,8735 gold badges49 silver badges99 bronze badges 2
  • 1 Side note: e: {...} should be e={...} – FZs Commented Aug 20, 2019 at 6:50
  • 1 But you must be sure that the keys are going to be available. Otherwise, you have to default the destructured object (parent). – Ioan Commented Aug 20, 2019 at 6:53
Add a ment  | 

1 Answer 1

Reset to default 12

You can destructure the value properties into distinctly named variables by placing the names after a :, e.g.

const {target: {userid: {value: myUserId}, password: {value: myPassword}}} = e;

myUserId will now have the value 'abc' and myPassword 'xyz'

本文标签: javascriptHow to destructure an object with multiple subkeys of the same nameStack Overflow