Converting JSON object into key-value array

Describe the problem/error/question

An HTTP request returns the following JSON:

[
  {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3",
    "key4": "value4"
  }
]

which I am trying to transform into an array like:

[
  {"key1": "value1"},
  {"key2": "value2"},
  {"key3": "value3"},
  {"key4": "value4"}
]

The following Javascript function works if I manually instantiate a variable with the same JSON as the HTTP result.

const keyValues= [
  {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3",
    "key4": "value4"
  }
];

function convertObjToArray(array) {
    const result = [];

    array.forEach(obj => {
        Object.keys(obj).forEach(key => {
            result.push({ [key]: obj[key] });
        });
    });

    return result;
}

return convertObjToArray(keyValues);

What is the error message (if any)?

However, when I try to use convertObjToArray($input.first()), I get errors ranging from Inconsistent item format, to forEach is not a function.

Please share your workflow

How do I transform the object’s values into an array?

Information on your n8n setup

  • n8n version: 1.47.1
  • n8n EXECUTIONS_PROCESS setting (default: own, main): default
  • Running n8n via (Docker, npm, n8n cloud, desktop app): npm
  • Operating system: Ubuntu 22.04

It looks like your topic is missing some important information. Could you provide the following if applicable.

  • n8n version:
  • Database (default: SQLite):
  • n8n EXECUTIONS_PROCESS setting (default: own, main):
  • Running n8n via (Docker, npm, n8n cloud, desktop app):
  • Operating system:

{{ Object.entries($input.first().json).map(([key, value]) => ({ [key]: value })) }}

1 Like

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