Checking a JSON for existing entries

I want to check if the JSON has a “date” and a “totalDuration”.
If it has both entries, the date should be returned.
If it has only one or none of the entries, an empty string should be returned.

What is wrong with the code that it does not work?

const event = $input.all();
let date = "";

for (const item of event) {
 if ( && item.json.totalDuration) 
   date =;

return {result: date};

Information on your n8n setup

Your conditional probably isn’t true (in this case) because the date and totalDuration keys are in different items. You’re currently checking if they’re in the same item. Naïvely you could do this (not sure how robust it will be if you have multiple incoming items though):

let date;
let totalDuration;

// Loop through all incoming items
for (const item of $input.all()) {
  // Set date if not currently truthy
  date ||=;
  // Set totalDuration if not currently truthy
  totalDuration ||= item.json.totalDuration;

if (date && totalDuration) {
  return {date}
} else {
  return {}
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.