I have an object
const complicatedObject = {
propertyA: {
property1: 1,
property2: 2
},
propertyB: {
property1: 1,
property2: 2
}
}
If I want to grab propertyA
I do
const { propertyA } = complicatedObject
console.log(propertyA) // { property1: 1, property2: 2}
If I want to grab propertyA's
property1
value I do
const { propertyA: { property1 } } = complicatedObject
console.log(property1) // 1
I can grab propertyA
and propertyA's
property1
this way.
const {
propertyA,
propertyA: {
property1
}
} = complicatedObject
console.log(propertyA) // { property1: 1, property2: 2}
console.log(property1) // 1
Is there a simpler way to get both propertyA
and property1
?
I read the following but I felt like nothing jumped out to me as being the answer.
Thanks!
Just use two separate destructuring statements like so:
const { propertyA } = complicatedObject;
const { property1 } = propertyA;
Demonstration:
const complicatedObject = {
propertyA: {
property1: 1,
property2: 2
},
propertyB: {
property1: 1,
property2: 2
}
}
const { propertyA } = complicatedObject;
const { property1 } = propertyA;
console.log(propertyA);
console.log(property1);
However, if you want to use the most concise code possible, and just wanted property1
's value (1
), you could use this method instead:
const { propertyA: { property1 } } = complicatedObject;
Demonstration:
const complicatedObject = {
propertyA: {
property1: 1,
property2: 2
},
propertyB: {
property1: 1,
property2: 2
}
}
const { propertyA: { property1 } } = complicatedObject;
console.log(property1);
Hopefully this helps!
This is the correct way:
const {
propertyA,
propertyA: {
property1
}
} = complicatedObject
If you want to access both propertyA and property1 without using multiple declaration.
console.log(propertyA) // { property1: 1, property2: 2}
console.log(property1) // 1
But if I were you, I would do just like:
const { propertyA } = complicatedObject
console.log(propertyA)
console.log(propertyA.property1)
Or, using multiple declaration:
const { propertyA } = complicatedObject,
{ property1 } = propertyA
console.log(propertyA, property1)
Actually, the purpose of your post is to question to use like:
const { propertyA: { property1 } } = complicatedObject
console.log(propertyA, property1)
And I would say, this is not possible. Because, constructuring object with colon just behaves an alias to the property. For eg.
const { propertyA: A } = complicatedObject
console.log(A) // works as if it is propertyA
console.log(propertyA) // won't work because propertyA is transformed to A
In similar,
const { propertyA: { property1 } } = complicatedObject
propertyA
is transformed to { property1 }
and can be accessed property1
.
Also an alias to property1
,
const { propertyA: { property1: prop1 } } = complicatedObject
console.log(prop1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With