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.date && item.json.totalDuration)
{
date = item.json.date;
break;
}
}
return {result: date};
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 ||= item.json.date;
// Set totalDuration if not currently truthy
totalDuration ||= item.json.totalDuration;
}
if (date && totalDuration) {
return {date}
} else {
return {}
}