So, I'm passing an object to an ES6 function that I'd like to destructure down to the parameter of a parameter. For example, the code below will log the data
prop of stuff
, but I'd like it to log the things
prop of data
of stuff
. So the correct answer would log [1,2,3,4]
. Not confusing at all, I know. Anyone know if this is possible?
const stuff = { data: { things: [1,2,3,4] } }; const getThings = ({ data }) => { console.log(data) }; getThings(stuff);
JavaScript Object Destructuring is the syntax for extracting values from an object property and assigning them to a variable. The destructuring is also possible for JavaScript Arrays. By default, the object key name becomes the variable that holds the respective value.
To destructure an array in JavaScript, we use the square brackets [] to store the variable name which will be assigned to the name of the array storing the element.
Nested Object and Array Destructuring Here's another example with an array of objects: You can destructure as deeply as you like: As you can see, keys a , b , and c are not implicitly defined, even though we pulled out nested values, firstElemOfC and remainingElementsOfC , from the array at c .
The rule of thumb is to start with the top-level and go down in the hierarchy until you reach the value you want to extract. Many times you may not know the property name (key) of an object while destructuring it.
The object destructuring can assign values to variables declared using const, let and var. Or even assign to an already existing variable. For example, here's how to destructure using let statement: I find it satisfying to combine for..of cycle with object destructuring to extract the property right away:
When a function returns an object and you are interested in specific property values, use destructuring straight away. Here is an example: It is similar to the basic object destructuring we saw in the beginning. You can use object destructuring with the for-of loop.
Yes, it is de-structured function parameter object. In your case parameters to Posts pass through Redux connect () function. Check your getPosts import and make sure it is not undefined.
Sure, here's how:
const stuff = { data: { things: [1,2,3,4] } }; const getThings = ({ data: {things} }) => { console.log(things) }; getThings(stuff);
As I correctly understood you, the correct answer is:
const getThings = ({ data: { things } }) => { console.log(things) };
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