-2

I have this JSON data here and I want to get all the data that corresponds to an id. EG: id 1 would contain service1 and 1.0. i need it to loop through however many lines there are and tell me the details for that id. EG: id1 contains service1 & 1.0, id2 contains service2 & 2.0 and so forth with however many lines there are.

[
  { id: 1, serviceName: 'Service1', serviceVersion: '1.0' }, 
  { id: 2, serviceName: 'Service2', serviceVersion: '2.0' },
  { id: 3, serviceName: 'Service3', serviceVersion: '3.0' },    
  { id: 4, serviceName: 'Service4', serviceVersion: '4.0' }    
]

I have gotten this far with actually selecting the data from the database and formatting it.

app.post("/check", (request, response) => {
    con.query('SELECT id, serviceName, serviceVersion FROM system_db.system', function (error, result) {
        var data = JSON.parse(JSON.stringify(result));
        console.log(data);
    });
});
starball
  • 20,030
  • 7
  • 43
  • 238
Braydan
  • 25
  • 6
  • I don't think the output of a query is in JSON format, I believe it is just an array and you don't need to use JSON.parse (btw, JSON.parse(JSON.stringify(array)) does nothing but copy the array). How about you just do result.filter((e) => e.id === idYouWantToFilterOn) ? – Emilien Dec 12 '22 at 08:52
  • Do you mean that you want to get the object from the array by matching it's `id` property? Where is the ID coming from? – Emiel Zuurbier Dec 12 '22 at 08:52
  • 1
    Does this answer your question? [Find object by id in an array of JavaScript objects](https://stackoverflow.com/questions/7364150/find-object-by-id-in-an-array-of-javascript-objects) – Mark Baijens Dec 12 '22 at 08:53
  • the original data from the database without being formatted is here: [ RowDataPacket { id: 1, serviceName: 'Service1', serviceVersion: '1.0' }, RowDataPacket { id: 2, serviceName: 'Service2', serviceVersion: '2.0' }, RowDataPacket { id: 3, serviceName: 'Service3', serviceVersion: '3.0' }, RowDataPacket { id: 4, serviceName: 'Service4', serviceVersion: '4.0' } ] – Braydan Dec 12 '22 at 09:22

1 Answers1

-3

I have solved my own question using some simple sql knowlegde!

app.post("/check", (request, response) => {
con.query('SELECT COUNT(id) AS id_count FROM system_db.system', function (error, result) {
    var data = JSON.parse(JSON.stringify(result));
    var count = data[0].id_count + 1;

    for (let index = 1; index < count; index++) {
        con.query('SELECT id, serviceName, serviceVersion FROM system_db.system WHERE id = ?', [index], function (error, result) {
            var data = JSON.parse(JSON.stringify(result));
            
        });
    }
});

});

Braydan
  • 25
  • 6