Don't override google sheets cell if output cell is empty

Hi @tom_firearc,

I don’t think there is a way to achieve that when mapping fields ‘manually’.
Even if you write an expression to check the source value and replace it with undefined/null, n8n still sends empty strings and clears the corresponding sheet cells:

See screenshots


To workaraound this I ended up writing a simple JS script to drop any empty keys before the Sheets node and configured the Sheets mapping to "Map Automatically’

See screenshots



This has the downside that your source data keys have to match the sheet columns exactly but it works.

Here is my script that drops the empty keys:
// Loop over input items
for (const item of $input.all()) {
  // Get the JSON object of the current item
  const json = item.json;
  const keysToRemove = [];

  // Loop through the keys of the JSON object
  for (const key in json) {
    // Check if the value of the current key is empty or undefined
    if (json[key] === '' || typeof json[key] === 'undefined' || json[key] === null) {
      // If it's empty or undefined, mark the key for removal
      keysToRemove.push(key);
    }
  }

  // Remove the marked keys from the JSON object
  for (const key of keysToRemove) {
    delete json[key];
  }
}

// Return the modified input items
return $input.all();

And here is an example of how to use it in a workflow:

If you find my answer helpful and if it resolves you issue please don’t forget to mark it as the solution :heart:

3 Likes