Home > Net >  How to add a new rows to an Array Object based on a condition in JS?
How to add a new rows to an Array Object based on a condition in JS?

Time:10-20

I have an array object like below

[
{
id: 123,
startdate: '2022-06-05',
enddate: '2023-04-05'
},{
id: 123,
startdate: '2021-06-05',
enddate: '2021-04-05'
}
]

I have to add a row isHistory based on the condition of startdate if it belongs to current year. Like in the above example, the result should be

[
{
id: 123,
startdate: '2022-06-05',
enddate: '2023-04-05',
isHistory: false
},{
id: 123,
startdate: '2021-06-05',
enddate: '2021-04-05',
isHistory: true
}
]

How can I acheive this? I am trying to map through the object but how do I compare the startdate on each iteration and add a new row, I am struggling in that.

Any suggestions?

CodePudding user response:

Use forEach to loop over the array and modify each object.

let array = [{
  id: 123,
  startdate: '2022-06-05',
  enddate: '2023-04-05'
}, {
  id: 123,
  startdate: '2021-06-05',
  enddate: '2021-04-05'
}];

const currentYear = new Date().getFullYear();
array.forEach(obj => obj.isHistory = obj.startdate.startsWith(currentYear));
console.log(array);

CodePudding user response:

You can compare the data as Date objects. Looking at your code I'm not sure if you correctly communicated your logic so my example shows how to determine if the current Date falls between the start and end Dates inclusively.

let array = [{
  id: 123,
  startdate: '2022-06-05',
  enddate: '2023-04-05'
}, {
  id: 123,
  startdate: '2022-01-05',
  enddate: '2022-06-05'
}, {
  id: 123,
  startdate: '2023-04-05',
  enddate: '2024-06-04'
}];

const today = new Date()
array.forEach(obj => {
  const startDate = new Date(obj.startdate)
  const endDate = new Date(obj.enddate)

  obj.isHistory = (today > endDate) // end date is in the past
  obj.isCurrent = ((today <= endDate) && (today >= startDate)) // before end, after start
  obj.isFuture = (today < startDate) // start date is in future
});
console.log(array);

CodePudding user response:

You can loop on the array and check for every object like this:

const arr = [
  {
    id: 1,
    startdate: "2022-06-05",
    enddate: "2023-04-05"
  },
  {
    id: 12,
    startdate: "2021-06-05",
    enddate: "2021-04-05"
  }
];
arr.map((item) => {
  if (item.startdate.includes("2022")) {
    item.isHistory = false;
  } else {
    item.isHistory = true;
  }
  return item;
});
  • Related