Adding additional rows to an Array Object in JavaScript based on a certain condition

I am faced with a scenario where I have an array object structured as follows

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

The task at hand is to introduce a new key isHistory based on whether the start date falls within the current year. Referring to the example above, the desired outcome should look like this

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

I am currently attempting to iterate through the object but I am struggling with how to compare each start date during the process and append a new entry. Any insights or suggestions on how to approach this challenge would be greatly appreciated.

Answer №1

Utilize the forEach method to iterate through the array and make changes to each object.

let items = [{
  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();
items.forEach(item => item.isRecent = item.startdate.startsWith(currentYear));
console.log(items);

Answer №2

If you need to compare Date objects, check out the sample code below that demonstrates how to determine if the current date is within a specified range. It seems like there might be some confusion in your code regarding logic implementation.

let dataset = [{
  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 currentDate = new Date()
dataset.forEach(item => {
  const startDate = new Date(item.startdate)
  const endDate = new Date(item.enddate)

  item.isHistory = (currentDate > endDate) // end date occurred in the past
  item.isCurrent = ((currentDate <= endDate) && (currentDate >= startDate)) // between start and end dates
  item.isFuture = (currentDate < startDate) // start date is in the future
});
console.log(dataset);

Answer №3

To iterate through the array and evaluate each object, you can utilize the following approach:

const data = [
  {
    id: 3,
    startdate: "2022-06-05",
    enddate: "2023-04-05"
  },
  {
    id: 15,
    startdate: "2021-06-05",
    enddate: "2021-04-05"
  }
];
data.map((element) => {
  if (element.startdate.includes("2022")) {
    element.isHistoric = false;
  } else {
    element.isHistoric = true;
  }
  return element;
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The behavior of Ajax is resembling that of a GET method, even though its intended method

Greetings, I am currently facing an issue while coding in Javascript and PHP without using jQuery for Ajax. My aim is to upload a file over Ajax and process it in PHP. Here is the code snippet: index.html <html> <head> <title>PHP AJAX ...

Issue with Axios code execution following `.then` statement

Recently diving into the world of react/nodejs/express/javascript, I encountered an interesting challenge: My goal is to retrieve a number, increment it by 1, use this new number (newFreshId) to create a new javascript object, and finally add this event t ...

PHP: How to Return a Multidimensional Array and Separate Variables Simultaneously

I am trying to send a 2D array with multiple individual variables from a PHP script to a JavaScript client using AJAX. Despite many attempts, I haven't been able to figure out how to include additional individual variables (like $var1, $var2, $var3) i ...

Issue with loading HTML file correctly in Django

I have been attempting to integrate my Django app with an admin dashboard from a repository on GitHub. After successfully logging in, the app redirects to the dashboard, but only the HTML part loads and none of the fancy features are visible on the dashboa ...

The index type 'X' is not allowed for use in this scenario

I encountered an issue in my TypeScript code: error message: 'Type 'TransitionStyles' cannot be used as an index type.' I'm wondering if there's a way to modify my interface so that it can be used as an index type as well: ...

Route parameters do not function correctly with computed properties

I'm facing an issue with my getter function that stores all products. When I try to retrieve a single product dynamically based on this.$route.params.id, it doesn't return any value. The code works fine when I navigate to a specific product, but ...

Encountered a type error while attempting to render and define table columns within a material table component in

Hey there! I'm currently using the Material table to create a table view, and here are the columns that I have defined: const columns: TableColumn[] = [ { title: 'TYPE', field: 'type_of_action', highligh ...

Exploring the Differences between Slim Framework's Currying and Dependency Injection

Frameworks like Angular allow for injecting services and controllers into each other, as shown in the code snippet below: App.controller('exampleController', function($scope, ajaxService){ ajaxService.getData().then(function(data) { ...

Error: The function $compile does not exist

Currently, I am working on developing an AngularJS directive using TypeScript. While testing my code in the browser, I encountered the following error: TypeError: $compile is not a function at compileComponent.js:14 Interestingly, the TypeScript compiler ...

Starting a fresh Angular project yields a series of NPM warnings, notably one that mentions skipping an optional dependency with the message: "npm

Upon creating a new Angular project, I encounter warning messages from NPM: npm WARN optional SKIPPING OPTIONAL DEPENDENCY: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="68e01b0d1e0d061c7518d7">[email protecte ...

Utilize the <a> element as a button to submit the data form

I am looking to transfer data from a form to another PHP page without using a button within the form itself. Instead, I have placed a separate button outside of the form for submission. How can I achieve this by sending the form data to the other page? Bel ...

What advantages does using immutablejs offer compared to using object.freeze?

I've scoured the internet trying to find convincing reasons for using immutablejs instead of Object.freeze(), but I still haven't found a satisfactory answer! What are the advantages of working with non-native data structures in this library ove ...

The variable "require" has not been declared in npm.js file at line

Apologies if this is a simple issue, but I have not been able to find a solution in my research. I am using the latest release of Bootstrap and have noticed a new file called npm.js compared to previous versions. All Bootstrap files are hosted locally on m ...

Minimize the cyclomatic complexity of a TypeScript function

I have a typescript function that needs to be refactored to reduce the cyclometric complexity. I am considering implementing an inverted if statement as a solution, but it doesn't seem to make much of a difference. updateSort(s: Sort) { if (s.ac ...

Using TypeScript to automatically determine the argument type of a function by analyzing the return type of a different function

I am working on an interface with the following structure: interface Res<R = any> { first?(): Promise<R>; second(arg: { response: R }): void; } However, I noticed that when creating a plain object based on this interface, the response ...

Cookies in Node.js Express are not being incorporated

Currently, I am in the process of developing a nodejs application and facing an issue with defining cookies. Here is a snippet of the code that I am working with: var app = express(); app.set('port', process.env.PORT || 3000); app.set('vie ...

An error was encountered involving an unexpected token < at the beginning of a JSON file while using express with firebase

After setting up an authentication system in express using firebase auth, I established an endpoint in my express server: app.post('/users/login', (req, res) => { console.log('logging in...'); firebase.auth().signInWithEmail ...

I am looking to modify the appearance of specific sections of a searched word in React.js, such as making them bold or lighter. Can anyone

After coming across several similar questions, I realized none quite matched my issue. Specifically, I am attempting to style only the part of the search result that relates to the entered query. For instance, if the query is "Thi", I want the result to di ...

Customizing the language parameter for the apply button script on LinkedIn

Our company's website features the AWLI button which allows users to apply for jobs using their LinkedIn profile. <div name="widget-holder"> <script type="text/javascript" src="https://www.linkedin.com/mj ...

Integrating new components into JSON data

I started by creating a JSON document in my code using the following syntax: let jsonData = []; To populate this document, I utilized the '.push()' method to add elements in this manner: jsonData.push({type: "example", value: "123"}); Eventua ...