简体   繁体   中英

Object destructing using ES6

I have this nested object that contains also an array.

result:{
"a": [{ "b": { "c": 1,
               "d": 2,
               "e": 3
              },
        "f": 0
      }]
}

How can I destructure this object using ES6 if I need the value of d?

Object destructuring notation is just like object literal notation, just on the other side of the equals sign. So you write exactly what you'd write to only create the structure necessary for d , and put your d variable/constant name there.

It looks like you're showing us the contents of your object (eg, it has a property called result ), so:

 const obj = { result: { "a": [{ "b": { "c": 1, "d": 2, "e": 3 }, "f": 0 }] } }; const { result: { "a": [{ "b": { d } }] } } = obj; console.log(d);

I'm not saying I'd use destructuring here. In fact, I probably wouldn't. But you can . :-)

If result was the variable containing the object, just remove that layer:

 const obj = { "a": [{ "b": { "c": 1, "d": 2, "e": 3 }, "f": 0 }] }; const { "a": [{ "b": { d } }] } = obj; console.log(d);

Of course, that's taking your question at face value that you want the d from the first entry in a . You can generalize it to get entry n like this (I'm back to assuming result is part of the object):

 const obj = { result: { "a": [ { "b": { "c": 1, "d": 2, "e": 3 }, "f": 0 }, { "b": { "c": 1, "d": 4, // *** "e": 3 }, "f": 0 } ] } }; const n = 1; // Which entry in `a` to get const { result: { "a": { [n]: { "b": { d } } } } } = obj; console.log(d);

I'm using object destructuring for a rather than array destructuring, with a computed property name. I can do that because arrays are objects.


Array destructuring notation is just like array literal notation, too. :-)

你想要 d 的值吗?

result.a[0].b.d ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM