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?
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 (e.g., 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. :-)