0

I have this array

const lists = [{id: 111, name: "list 1"}, {id: 332, name: 'list 2'}, ...];

From it, I want to generate an array of just list names. Here is the desired result:

["list 1", "list 2", ...] 

Currently, I do this with

const list_names = lists.map(x => x.name);

and there are no problems with this code. Nor am I philosophically opposed to doing it that way. I am only asking out of curiosity: can I accomplish this using desctuturing? Something along the lines of this:

const [{name}] = [{id: 111, name: "list 1"}, {id: 332, name: 'list 2'}];

Obviously, this will only descructure the name key of the first element of the array, but is there a way to do something like this (conceptually):

const [{[name]}] = [{id: 111, name: "list 1"}, {id: 332, name: 'list 2'}];

Also, this is NOT what I am looking for: Destructuring array of objects in es6

codemonkey
  • 7,325
  • 5
  • 22
  • 36
  • I don' think that you use array destructuring in the way you want to use it. Here using the map operation would be a good choice – Aalexander Feb 03 '21 at 07:30
  • Pretty good question, but the answer will be no, as destructuring won't get data from all items as you wrote. If you have the exact number of items in the array, then you can do destructuing for each items specifically. – Dominik Matis Feb 03 '21 at 07:30
  • 3
    Destructuring doesn’t perform mapping; this isn’t possible, currently. What I like to do, to generalize getting a specific property of objects, is to define `function getProp({ [this]: prop }){ return prop; }`, then `.map(getProp, "name")` (make sure strict mode is on). Alternatively, use method notation: `const { getProp } = { getProp({ [this]: prop }){ return prop; } };`. – Sebastian Simon Feb 03 '21 at 07:31
  • 1
    Destructuration is for a fixed structure of data. Since an array can contains as much number of element as you want, I don't think destructuring is the best fit. Also what's the point? `.map( x => x.name)` is already the shortest synxtax. What are you trying to achieve? – Thanh Trung Feb 03 '21 at 07:33
  • `lists.map(({name})=>name)` is not short enough? – mplungjan Feb 03 '21 at 07:39
  • 1
    Remember that the *destructuring assignment* (as is the full name of the feature) is just what it says - an assignment. You're supposed to destructure something into a discrete set of variables. It's not changing anything about the shape of the object other than taking a subsection of it and giving that value to a variable. Object destructuring is *always* an alternative of `x = obj.a.b.c` in some fashion, while array destructuring doesn't exactly conform (actually calls the iterator) conceptually the result would be like using indexes. – VLAZ Feb 03 '21 at 07:40

0 Answers0