Stack Exchange
What is the correct syntax to destructure object in JS while mapping over array?
I have an array of objects and I want to .map() over the array while destructuring elements. Is there a way to achive it?
I currently have:
const nav = documents.map((category, index) => {
        const categoryName = category.data.category_name[0].text;
        console.log(index);
        return categoryName;
    });

I want to achieve:
const nav = documents.map((*destructure here so I get .text property*, index) => {
        const categoryName = category.data.category_name[0].text;
        console.log(index);
        return categoryName;
    });

edit: please note I do need index index too.

Not really sure that such deep destructuring is possible

Closest i can think of is going up to the category_name

That's possible @ManosKounelakis you can mix object and array destructuring

@jonrsharpe I haven't tried destructuring at this level. I would like to see an example to wrap my head around

I'd suggest you both check out https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment. And do it one step at a time, move one "layer" from inside the function to the parameter.

If you're in a team, your team will hate you for writing arguments like that...

@andymccullough couldn't agree more with you. I love the idea that you can do extreme thinks like that. It helps you learn and i've done it my self. At some point though you will have to ask your self if all that fancy code can be easily maintained

You can do it as long as you only want index 0 of the category_name arrays. You simply use array destructuring at that level to assign a variable from that index. And that variable is inside another destructured object.


documents = [{
  data: {
    category_name: [{
      text: "Title 1"
    }]
  }
}, {
  data: {
    category_name: [{
      text: "Title 2"
    }, {
      text: "Title 3"
    }]
  }
}];

const nav = documents.map(({
  data: {
    category_name: [{
      text: category_name
    }]
  }
}, index) => {
  console.log(index);
  return category_name;
});

console.log(nav);



As you can see, the destructuring pattern is just like the object literal, except that you replace the value you want to grab with the variable.

Not OP here. I would like to know what would happen if you needed to use an index other than 0 let's say 1

category_name: [ignore, {text: category_name}] will capture index 1.

this is exactly what I wanted, works perfectly; however now I am a bit concerned about readability of the code.

If you just want a single variable, complex destructuring probably isn't worth it. It's more useful if you want to extract many items from the structure. Multi-level destructuring can also be confusing.

It's also unusual that you only want one array element.
