Transforming data to an array, based on conditional data

Describe the problem/error/question

Hi team - looking for some help on this one, and i’m not great with the function node yet: I have data that will be provided to me that I need to transform into an array such as below: However, when one of the item amounts is zero, I need to remove that item from the array. FYI - I will receive the topic and the amount, but I need help building the array, and conditionally removing an item if the amount is zero.

[
{
“name”:“Lights”,“amount”:“20”
},

{ “name”:“Building”,“amount”:“30”
},

{ “name”:“Other”,“amount”:“40”
},

{ “name”:“Water”,“amount”:“0”
},

{ “name”:“Phone”,“amount”:“0”
}
]

Hi @itpastor :wave: Can you also let us know what your source data is looking like, so we can try to help you out with this? If you could provide that in JSON format, that would be really helpful :+1:

2 Likes

Yes - this may be more helpful. I need to transform this string into an array.

I need to transform this:
[
{“tithes”:70,“offering”:80,“love_offering”:30,“building”:50,“other”:60}
]

Into this:

[{“name”:“Tithes”,“amount”:“70”}, {“name”:“Building”,“amount”:“50”},{“name”:“Other”,“amount”:“60”},{“name”:“Offering”,“amount”:“80”},{“name”:“Love Offering”,“amount”:“30”}]

1 Like

Hi @itpastor :wave:

Assuming this data is coming from the previous node, you could use the following:

const inputData = items[0].json;

const transformedData = Object.entries(inputData)
  .sort((a, b) => a[0].localeCompare(b[0]))
  .map(([name, amount]) => ({ name: name.replace('_', ' '), amount: amount.toString() }));

return transformedData.map(item => ({ json: item }));

That will output your first provided array sorted like this, which is what I believe you’re looking for (but in alphabetical order):

[
  {
    "name": "building",
    "amount": "50"
  },
  {
    "name": "love offering",
    "amount": "30"
  },
  {
    "name": "offering",
    "amount": "80"
  },
  {
    "name": "other",
    "amount": "60"
  },
  {
    "name": "tithes",
    "amount": "70"
  }
]
2 Likes

This is perfect! Thanks!

2 Likes

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