How can I combine all objects in an array into one object?

Hey!
Concatenate all objects in the array into one object.

To get it like this:

Hey @Roket,

You can reuse the code from here:

Thanks, @harshil1712!

I’ve looked at this page before.
This documentation does not contain an example with a solution to my problem.
I need to create one new object instead of an array of objects.

Hey @Roket,
Ah, yes. I shared that with you as a reference. You will of-course have to modify the code for your use case :slight_smile:

@Roket Your function node node should look like:

const results = []

for (const item of items) {
    let data = item.json.data;
    
    data = data.reduce((obj, value) => Object.assign(obj, { [`${Object.keys(value)[0]}`]: Object.values(value)[0]}), {});
  
    results.push({
      json: {
        ...item.json,
        data
      }
    })
}

return results
Example workflow
{
  "nodes": [
    {
      "parameters": {},
      "name": "Start",
      "type": "n8n-nodes-base.start",
      "typeVersion": 1,
      "position": [
        -550,
        70
      ]
    },
    {
      "parameters": {
        "functionCode": "return [\n  {\n    json: {\n      status: 'open',\n      data: [\n        {\n          key: 'value',\n        },\n                {\n          key2: 'value',\n        }\n      ]\n    },\n  },\n    {\n    json: {\n      status: 'open',\n      data: [\n        {\n          key: 'value',\n        },\n                {\n          key2: 'value',\n        }\n      ]\n    },\n  }\n]"
      },
      "name": "Function",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [
        -310,
        70
      ],
      "notesInFlow": true,
      "notes": "Mockup data"
    },
    {
      "parameters": {
        "functionCode": "const results = []\n\nfor (const item of items) {\n    let data = item.json.data;\n    \n    data = data.reduce((obj, value) => Object.assign(obj, { [`${Object.keys(value)[0]}`]: Object.values(value)[0]}), {});\n  \n    results.push({\n      json: {\n        ...item.json,\n        data\n      }\n    })\n}\n\nreturn results\n\n"
      },
      "name": "Function1",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [
        -110,
        70
      ]
    }
  ],
  "connections": {
    "Start": {
      "main": [
        [
          {
            "node": "Function",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Function": {
      "main": [
        [
          {
            "node": "Function1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}
1 Like

@RicardoE105, Thanks a lot as always!

1 Like