Remove character in an array nested string JSON

Suppose I have an API returning:

{
  "results": [
    {
      "concatId": "1234",
      "keywords": "foo — bar — baz — qux — quux"
    },
    {
      "concatId": "5678",
      "keywords": "aaa — bbb — ccc — ddd — eee"
    }
  ]
}

My need

I want to replace the in every "keywords" strings by a ,. Currently, I can achieve this using the workflow down below, but not looping it on every object.

The issue is that I don’t know how to iterate that function over each objects nested in that array.

// The input used is the payload returned by the HTTP request
$node["HTTP Request"].json["results"][0]["keywords"]

Here the [0] is the index value.

How can I replace the character I want in each objects of the array when the index value is fixed?

Note

My question is very vague and I’m fully aware of it. I don’t know how to properly explain and describe my need, so do not hesitate to ask for more details/screenshots/workflows example.

Hi,

If I’m understanding correctly, you could do this a few different ways but here is an example:

item.results.forEach((result, i) => {
    item.results[i] = item.results[i].keywords.replaceAll('—',',');
});

This is using shorthand for the function definition, you can learn more on the Mozilla Developer Javascript Reference for Array.prototype.forEach().

If you wanted to go old school, here is the same but using a simple Javascript for:

for (var i = 0; i < item.results.length; i++) {
    item.results[i] = item.results[i].keywords.replaceAll('—',',');
}

You should also be aware of the difference between the Function and Function Item nodes. It looks to me for your ‘Search & Replace’ node you’re using a Function node where a Function Item node would work.

If you do actually want to split out the results from the API call into individual items, the Function node is the correct one to use.

In that case, you need to have a ‘nested for’ in your ‘Find & Replace’ node:

var results = [];

for (const item of items) {
    for (const result of item.json.results) {
        for (const keyword of result.keywords.split(' — ')) {
            results.push({
                json: {
                    keyword
                }
            });
        }
    }
}

return results;

Hope this helps.

2 Likes

Works perfectly, thanks for the great help.