TheLearner
TheLearner

Reputation: 2863

How to destructure an object with multiple sub-keys of the same name

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?

Upvotes: 5

Views: 2098

Answers (1)

Jonas Høgh
Jonas Høgh

Reputation: 10874

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'

Upvotes: 12

Related Questions