In its main form, having an array of objects:
let arr = [ {val:"a"}, {val:"b"} ];
How can you use destructuring to get only the values ['a', 'b'] .
getting the first value is easy:
let [{val:res}] = arr;
Getting all the values ββinside the array can be done using the rest statement:
let [...res] = arr;
By combining those, I expected that I could use:
let [...{val:res}] = arr; //undefined, expected all 'val (['a', 'b'])
The above returns undefined (checked in FF). Some additional testing seems to indicate that adding a rest statement when using object destructuring also does not use iteration, but returns the original object, for example. let [...{length:res}] = arr; //res= 2 let [...{length:res}] = arr; //res= 2 . Some other tests, such as let [{val:...res}] = arr; or let [{val}:...res] = arr; cause syntax errors.
It is quite simple to do this with other methods, such as using map in an array, but basically I stumble upon this problem while destroying several levels (an array with objects that have their own property that contains the array). So I'm really trying to get around how to do this only with destructuring. For convenience: test script
change
My apologies if I do not explain the purpose of the question. I am not looking for a solution to a specific problem, only to find the correct syntax to use for destruction.
Otherwise, the first question will be: in the example above, why let [...{val:res}] = arr; does not return all values ββ( ['a', 'b'] ). The second question: what is the correct syntax for using the rest operator with the restructuring of nested objects? (pretty sure I have some definitions mixed here). It seems that the latter is not supported, but I have not come across any documentation that (and why) will not.
javascript destructuring
Me.Name
source share