1

I have an array called dateArray, which consists of MomentJS objects with dates of the current week. I then render them in HTML using a for:each template, and set a onClick handler.

getDates(startDate, endDate) {
   while (startDate <= endDate) {
    this.dateArray.push(moment(startDate));
    startDate = moment(startDate).add(1, "days");
   }
  window.console.log(this.dateArray);
}

This logs the dateArray as an Array of MomentJS objects, which is good.

I then render a table in HTML using the for:each template.

<template for:each={dateArray} for:item="day" for:index="index">
  <td
    key={day}
    data-index={index}
    data-day={day}
    onclick={handleStart}
  ></td>
</template>

However, console.logging dataset.day gives me: "Mon Feb 17 2020 00:00:00 GMT+0100", instead of the MomentJS object.

  handleStart(event) {
    window.console.log(event.target.dataset.day);
  }

Normally in Javascript I could do a forEach(), create a div and set an attribute to the item of the array.

The only other solution I found was using the index of the item and query the array but not sure if that's the best option.

window.console.log(this.dateArray[event.currentTarget.dataset.index])

Is there any way to pass a Javascript object as an attribute in a for:each template and return the entire Object?

1 Answer 1

1

Is there any way to pass a Javascript object as an attribute in a for:each template and return the entire Object?

No. Data attributes are always string values. This is a limitation of the DOM model. You are correct in thinking that you need to go back to the source data in order to get the actual moment object.

1
  • Reluctantly accepting this as an answer then :) Since I am able to do something in regular Javascript like div.whateverAttribute = item with a forEach loop, I was hoping that LWC had something similar.Thanks for answering! Commented Feb 16, 2020 at 17:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .