Saturday 1 April 2017

for loop comparing two objects not working properly in javascript

I have a snippet of code that is not working as expected...

for(let a in html){

    // check if first time (empty json)
    if(JSON.stringify(dbdata) === '{}'){
        console.log('new id found', a);
        newIdsFound[a] = html[a];
        dbdata[a] = html[a];
    }

    for(let b in dbdata){

        if(a == b){
            console.log('id exists, skipping...', a);
        }else{
            console.log('new id found', a);
            newIdsFound[a] = html[a];
            dbdata[a] = html[a];
        }

    }
}

but this is what I get in the console:

id exists, skipping... 9912
new id found 9912
new id found 9912
new id found 9912
new id found 9912
new id found 9912
new id found 10077
id exists, skipping... 10077
new id found 10077
new id found 10077
new id found 10077
new id found 10077
new id found 10188
new id found 10188
id exists, skipping... 10188
new id found 10188
new id found 10188
new id found 10188
new id found 10267
new id found 10267
new id found 10267
id exists, skipping... 10267
new id found 10267
new id found 10267
new id found 10271
new id found 10271
new id found 10271
new id found 10271
id exists, skipping... 10271
new id found 10271
new id found 10309
new id found 10309
new id found 10309
new id found 10309
new id found 10309
id exists, skipping... 10309

I am running this code while the json dbdata is still empty but I cannot make it properly working.

After a first population it should skip existing entries but I am doing something wrong..

the code is intended to being executed more times in the future... if there aren't new entries it should skip to make additions, at least it is my ideal behaviour

I am keeping separated objects (dbdata and newIdsFound) so newIdsFound can keep track of the new additions only


Edit: this is an example input of the data I have:

"10271":"<a href=\"http://blabla.com?q=10271\">texthere.\n</a>",
"99999":"<a href=\"http://blabla.com?q=99999\">othertxt.\n</a>",
etc...



via neoDev

No comments:

Post a Comment