0

I'm writing a function that pulls data out of a SQLite database, parses the information into a Javascript array and formats it into the format that the application I'm working on is expecting and pushes the new formatted data into an array to be sent to our front end. However, whenever I receive the information on the front end, I have the right array length, but it's using the last value of the array.

Here is the body of my function

EDIT: For the sake of the example, I am using the better-sqlite3 library.

var optionalParams = "";
if(area != null){
    optionalParams = ` WHERE areaId = ${area}`
}
let itemsToSend = [];
for (const driver of drivers){
    let table = `TABLE`
    let dbReturn = database.prepare(`SELECT * FROM ${table}${optionalParams}`).all();

    for(const row of dbReturn){
        let item = {...driver}
        item.name = row.name;
        item.id = row.id;
        item.area = row.name
        item.instanceId = row.instanceId; 
        itemsToSend = [...itemsToSend, item];
    }
};
return itemsToSend;

I've done enough research to know that this should work in series, so could someone explain to me why this isn't working the way please?

Lennholm
  • 7,205
  • 1
  • 21
  • 30
  • 2
    What's wrong with using `itemsToSend.push(item)` instead of `itemsToSend = [...itemsToSend, item]`? – Bucket Dec 11 '18 at 18:07
  • What is `database.prepare`? Seems like you forgot to mention what sort of library you're using. – connexo Dec 11 '18 at 18:08
  • I’ve tried itemsToSend.push(item) too. This iteration of the function I tried something different. – basicallysteve Dec 11 '18 at 18:08
  • 1
    That looks an awful lot like an SQL injection vulnerability...and without knowing what `database.prepare` is/does there's no way we can possibly help you. – Jared Smith Dec 11 '18 at 18:14
  • What is `drivers` in this case? It could be that mixing synchronous API of better-sqlite3 is not playing nicely with asynchronous API of whatever the other object is. – cmbuckley Dec 11 '18 at 18:18

0 Answers0