ERROR: products.flatMap is not a function

Hi, I get an error when trying to call a function.

Function:

let products = item

const res = products
  .flatMap(Object.entries)
  .map(([ id, props ]) => (  { ...props, id }));

return res

I am getting this error

ERROR: products.flatMap is not a function [Line 4 | Item Index: 0]



.
I’m trying to do an API integration with an online store
I download a list of products from the store via HTTP request.
I get this object:

[
{
"error": {
"code": 0,
"message": "OK",
"fields": []
},
"method": "listProducts",
"result": {

    "2": {
      "name": "Name of product with id 2",
      "ean": "123123123",
      "parameters": []
      },
    "3": {
      "name": "Name of product with id 3",
      "ean": "123123122",
      "parameters": []
      },
    "5": {
      "name": "Name of product with id 5",
      "ean": "123123121",
      "parameters": []
      }
  }
]

I call the function:


return item.result

As a result, I get:

[
  {
    "2": {
      "name": "Name of product with id 2",
      "ean": "123123123",
      "parameters": []
      },
    "3": {
      "name": "Name of product with id 3",
      "ean": "123123122",
      "parameters": []
      },
    "5": {
      "name": "Name of product with id 5",
      "ean": "123123121",
      "parameters": []
      }
  }
]

I need to get an object like this

[
  {
    "id": "2",
    "name": "Name of product with id 2",
    "ean": "123123123",
    "parameters": []
  },
  {
    "id": "3",
    "name": "Name of product with id 3",
    "ean": "123123122",
    "parameters": []
  },
  {
    "id": "5",
    "name": "Name of product with id 5",
    "ean": "123123121",
    "parameters": []
  }
]

I need to get an object like this, so in the end I tried to achieve this through JavaScript but I get an error

ERROR: products.flatMap is not a function [Line 4 | Item Index: 0]

Hi @iNeeR, welcome to the community!

.flatMap() would require an array, but your result field seems to be an Object. So my suggestion would be to iterate through each key of your object ("2", "3", "5"), for example like so:

Would this work for you?

@MutedJam The solution works great, but do you have any idea how to move the key to value as “id” value?

Sure thing, sorry for missing this earlier:

If you want ID to be an integer you could wrap it in .parseInt(), the Function code would then look like so:

const products = items[0].json.result;

let results = [];

for (productKey of Object.keys(products)) {
  let result = {
    json: {
      id: parseInt(productKey)
    }
  };
  Object.assign(result.json, products[productKey]);
  results.push(result);
}

return results;

1 Like

Thanks a lot, it works awesome

1 Like