Ericel Ericel - 2 months ago 8
Javascript Question

How can I check for equivalent in javascript object keys

I have this object, I want to make such users don't add other items to database , when there is an item in object with the same key name.

{
"0360841d73bd74b268dcc3abad2555c0": {
"file_dislikes": 0,
"file_likes": 0,
"slang": "mmmmmmmmm",
"slangDefine": "dddddddddd",
"slangExample": "ddddddd",
"slangID": "0360841d73bd74b268dcc3abad2555c0",
"time_date": "2016-09-15T16:28:19.384Z",
"user_id": "0Uwx4oXQVEckArRSZNerwhfDZFF3"
},
"072794611d87924ac134bc87ae202c05": {
"file_dislikes": 0,
"file_likes": 0,
"slang": "damnit",
"slangDefine": "Damnit",
"slangExample": "Damnit",
"slangID": "072794611d87924ac134bc87ae202c05",
"time_date": "2016-09-14T13:40:47.745Z",
"user_id": "bHDKSU6aorX9efzBCHyVI4JBTh53"
}
}


I have the items in the object vm.slangs

for (var keys in vm.slangs) {
var getThisObject = vm.slangs[keys];
if ((getThisObject.slang).toLowerCase() === ("Damnit").toLowerCase()) {
console.log("there is a slang with that name!");
// Item cannot be added to database.
}
}


I thought this should work , but it doesn't maybe I am doing something wrong.

Answer

You need a flag and exit the loop, if the slang is found and prevent an insert into the db.

var unique = true;

for (var keys in vm.slangs) {
    var getThisObject = vm.slangs[keys];
    if (getThisObject.slang.toLowerCase() === "Damnit".toLowerCase()) {
        console.log("there is a slang with that name!");
        unique = false;
        break;
    }
}
if (unique) {
    // add to db
}