DEV Community

Olen Daelhousen
Olen Daelhousen

Posted on

7 2

Destructuring When Using Array.prototype.map() on an Array of Objects in React

In the web application I am building, I often loop through arrays of objects that are returned from an application programming interface (API) and display the data on the front-end using React. The following is an example JSON response from the API:

[
  {
    "id": 42,
    "addressee": {
      "id": 98,
      "firstName": "James",
      "lastName": "Deacon",
      "photoLink": "images/IMG_3598.JPG",
      "city": "Atlanta",
      "state": "GA",
      "country": "United States",
      "createdAt": "2019-12-23T00:33:11.000Z",
    },
  },
  {
  "id": 43,
  "addressee": {
    "id": 99,
    "firstName": "Billy",
    "lastName": "Gato",
    "photoLink": "/images/IMG_9923.JPG",
    "city": "Chattanooga",
    "state": "TN",
    "country": "United States",
    "createdAt": "2019-10-13T04:22:42.000Z",
    }
  }
]

I use React to map the above data retrieved from the API and pass it to a Card component as props, as shown below.

return(
  <div className="list">
    {list.map(element => (
      <div className="card" key={element.id}>
        <Card
          addresseeId={element.addressee.id}
          firstName={element.addressee.firstName}
          lastName={element.addressee.lastName}
          photoLink={element.addressee.photoLink}
          city={element.addressee.city}
          stateCode={element.addressee.stateCode}
          createdAt={new Intl.DateTimeFormat("en-US", {
            year: "numeric",
            month: "long"
          }).format(new Date(element.addressee.createdAt))}
        />
      </div>
    ))}
  </div>
)

Repeatedly copy and pasting "element.addressee" got to be tiresome, so I started thinking about how to use ES6's destructuring to make things less repetitive. The first thing I tried was the traditional const { x, y } = element pattern, but ESLint complained about "const". So I did some searching, but did not find much about how to destructure the current element in Array.prototype.map() in JSX.

I almost gave up, but finally resorted to reading the documentation and stumbled on assignment without declaration, where a variable can be assigned its value separately from its declaration. With this syntax ({ x, y } = element) is valid, just like const { x, y } = element. In the case of Array.prototype.map(), array.map(({ x, y }) => { //callback function }); will destructure element and assign x and y. The below code snippet shows how I used this to refactor the card component and skip typing "element.addressee" several times.

return(
  <div className="list">
    {matchesFilteredByStatus.map(
      ({ id, addressee: {
        id: addresseeId,
        firstName,
        lastName,
        photoLink,
        city,
        stateCode,
        createdAt}, }) => (
      <div className="card" key={id}>
        <Card
          addresseeId={addresseeId}
          firstName={firstName}
          lastName={lastName.substring(0,1) + "."}
          photoLink={photoLink}
          city={city}
          stateCode={stateCode}
          createdAt={new Intl.DateTimeFormat("en-US", {
            year: "numeric",
            month: "long"
          }).format(new Date(createdAt))}
        />
      </div>
    ))}
  </div>
)

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (1)

Collapse
 
khaife profile image
K_A

Great Article managed to explain something I had difficulty putting into words.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️