Search code examples
javascriptarraysdestructuring

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.


Solution

  • 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.