Adding Property When Undefined

I am pulling data via SmartSheet API and not all objects have the property “value” defined. I am struggling a bit with the required Javascript to add the “value” property when not present within an object.

With my current workflow, I am getting a "Cannot set properties of undefined (setting ‘value’) in the CODE node when it hits the first instance of an undefined “value” property

Here is input data to the Code2 Node:

{

“id”:275169835870084,

“rowNumber”:1,

“expanded”:true,

“createdAt”:“2022-11-28T08:49:32Z”,

“modifiedAt”:“2023-01-26T12:04:49Z”,

“cells”:[

{

“columnId”:2940315076192132,

“value”:“Danley Sound Labs”,

“displayValue”:“Danley Sound Labs”

},

{

“columnId”:7443914703562628

},

{

“columnId”:1814415169349508,

“value”:“July”,

“displayValue”:“July”

}
]


The expected output is as follows:

{

“id”:275169835870084,

“rowNumber”:1,

“expanded”:true,

“createdAt”:“2022-11-28T08:49:32Z”,

“modifiedAt”:“2023-01-26T12:04:49Z”,

“cells”:[

{

“columnId”:2940315076192132,

“value”:“Danley Sound Labs”,

“displayValue”:“Danley Sound Labs”

},

{

“columnId”:7443914703562628,
“value”: " "

},

{

“columnId”:1814415169349508,

“value”:“July”,

“displayValue”:“July”

}
]

Any help would be greatly appreciated!

Information on your n8n setup

  • **n8n version: 0.210.1
  • **Database you’re using (default: SQLite): SQLite
  • **Running n8n with the execution process [own(default), main]:own
  • **Running n8n via [Docker, npm, n8n.cloud, desktop app]:Docker

Hi @chadgriff1, I’d probably use the Run Once for Each Item mode of the Code node here to simplify things a bit. Like so:

In this workflow I have removed the nodes that aren’t part of the problem and have switched to a boolean condition on the IF node (otherwise you might end up with an endless loop).

The actual code adding the single whitespace in the value property is quite simple:

for (cell of $input.item.json.cells) {
  cell.value = cell.value || ' ';
}

return $input.item;

So I am simply looping through all cells of the input item, then set cell.value to either the existing value or if it is falsy to the empty whitespace. This is called a short-circuit evaluation.

Hope this helps!

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