Search code examples
node.jsnode-fetch

Looping through API response Node JS


I'm trying to pull data from an API and insert it into a MySQL Database. The API has over 100 objects but I can't find any information on how to do this?

I'm using node-fetch to output the Json Data but can't loop through each object? I've added a snippet of the API.

[
  {
    "id": 1,
    "name": "Device_1"
  },
  {
    "id": 2,
    "name": "Device_2"
  }
]

Solution

  • Worked it out, should have known now that I look at it, but to help anyone in the future I'll leave the solution.

    const fetch = require('node-fetch');
    
    let settings = {
        method: "Get"
    };
    
    fetch('http://127.0.0.1:3000/test', settings)
        .then(res => res.json())
        .then((json) => {
            for (var i = 0; i < json.length; i++) {
                json.id = json[i].id;
                console.log(json.id);
            }
        });