0

Firstly, I am not an expert in JS. Still learning and I have the following code and all I needed to do is console the laeve.name, leave.count... as mentioned in the latter part of the code. But it becomes undefined all the time.

Data.forEach(async (element) => {
  let newleaveData = {};
  newleaveData.leave_id = element.leave_id;
  let leave = this.state.allLeaves.filter((e) => e.id === element.leave_id);
  let requestedArr = MainArray.filter((el) => el.leave_id === element.leave_id);

  if (leave.leave_counter === "Years" || leave.leave_counter === "Months") {
    newleaveData.leaveCounter = "Months";
  } else {
    newleaveData.leaveCounter = "Days";
  }
  if (requestedArr.length > 0) {
    newleaveData.leaveName = leave.name;
    console.log("leave obj:" + JSON.stringify(leave, null, 2));
    console.log("leave name:" + leave.name);
    console.log("leave count:" + leave.no_of_leaves);
    console.log("leave counter:" + leave.leave_counter);

I have tried to await the filter function since the whole function is an async one. But it's not working. I would be very much thankful if someone can mention the mistake in this code.

frogatto
  • 28,539
  • 11
  • 83
  • 129
  • Can you include some more context regarding the expected data? – johnkhigginson May 18 '23 at 06:10
  • 2
    `filter()` returns an array. You probably meant to use `find()` – Phil May 18 '23 at 06:15
  • I think you should familiarise yourself with the functions you're using. See [Array.prototype.find()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find), it may return `undefined` if nothing matches the predicate – Phil May 18 '23 at 06:30
  • @johnkhigginson I am expecting leave data which matches with the this.state.allLeave to make newLeaveData variable with some field manipulations. All I wanted to know is why these fields are getting undefined even the state contains data. As I think, data which is in the state is not assigning to the leave array. Thats why I tried to await the this.state.allLeaveData.filter() function. – Dev Nishan May 18 '23 at 06:34
  • @Phil now it says TypeError: Cannot read properties of undefined (reading 'leave_counter') – Dev Nishan May 18 '23 at 06:37
  • @Phil Thanks for the support. I have referred the link you provided and fixed the issue. Is there any option to make your comment as the correct answer and close this question. Because I haven't found any option to make the comment as the correct answer. – Dev Nishan May 18 '23 at 07:00
  • Does this answer your question? [How to find first element of array matching a boolean condition in JavaScript?](https://stackoverflow.com/q/10457264/283366) (somebody else could vote to close as a duplicate) – Phil May 18 '23 at 07:01

0 Answers0