Split and handling null

Describe the issue/error/question

With the help of this forum and some logic, I performed data transformations (serializing items and replacing strings). However, I’m stuck with splitting strings from a key and inserting the split indices back into their respective object. (refer to “Expected JSON”)

Data transformation node

const serialItems = [];

for (const element of items[0].json) {
  serialItems.push({json: { ...element, COUNT: element.COUNT.replace('+', '').replace('-', '')}});
  
}

return serialItems;

Split logic tried

let splitItems = [];

for (item of items) {
  myValues.push(...item.json.ToSplit.split(' '));
}
return myValues.map(e => {
  return {
    json: {
      key: e.trim()
    }
  };
});

Please share the workflow

mock data and logic node

Share the output returned by the last node

Input mock JSON
[
[
{
"COUNT": "+1-1",
"KEY1": "Example1",
"ToSplit": "Test A"
},
{
"COUNT": "+2-1",
"KEY1": "Example2",
"ToSplit": "Test B"
},
{
"COUNT": "+3-1",
"KEY1": "Example3",
"ToSplit": null
}
]
]
Output JSON
[
{
"COUNT": "11",
"KEY1": "Example1",
"ToSplit": "Test A"
},
{
"COUNT": "21",
"KEY1": "Example2",
"ToSplit": "Test B"
},
{
"COUNT": "31",
"KEY1": "Example3",
"ToSplit": null
}
]
Expected JSON
[
{
"COUNT": "11",
"KEY1": "Example1",
"ToSplit": "Test A",
"Split_value_1": "Test",
"Split_value_2": "A"
},
{
"COUNT": "21",
"KEY1": "Example2",
"ToSplit": "Test B",
"Split_value_1": "Test",
"Split_value_2": "B"
},
{
"COUNT": "31",
"KEY1": "Example3",
"ToSplit": null,
"Split_value_1": "", //assuming inserting empty strings is recommended
"Split_value_2": ""
}
]

The output returned by the split logic above will make a new object of every split value, thereby doubling the no. of items, which is undesired, as we want to insert split values into their respective object itself.

Thank you for your time and valuable pointers!

If you are OK with just an array of the split values, instead of keys you can use this in you second function:

const serialItems = [];

for (const element of items[0].json) {
  serialItems.push({json: { ...element, COUNT: element.COUNT.replace('+', '').replace('-', '')}});
}

// Split field ToSplit into array
for (item of serialItems) {
  item.json.split = item.json.ToSplit?.split(' ') || []
}

return serialItems;

Which would give you

[
  {
    "COUNT": "11",
    "KEY1": "Example1",
    "ToSplit": "Test A",
    "split": [
      "Test",
      "A"
    ]
  },
  {
    "COUNT": "21",
    "KEY1": "Example2",
    "ToSplit": "Test B",
    "split": [
      "Test",
      "B"
    ]
  },
  {
    "COUNT": "31",
    "KEY1": "Example3",
    "ToSplit": null,
    "split": []
  }
]
2 Likes

Snippets like these help me understand more about JSON and n8n on the fly. Thank you very much!

1 Like