Reputation: 2880
I have this code where I find keys where the string values are separated by comma
var db = {
"name": "Nkosana",
"middle": "Baryy",
"surname": "walked",
"batch_number": "test,b",
"temp": ",,67,6,87,86,5,67865,876,67",
"integrity": ",,,,,,,,,,,,,,,,,,,,,,,",
"weight": "760,765,755,758,759,758,758,769,758,762,759,7",
"comment": "oh la la",
};
for (var key in db) {
if (db.hasOwnProperty(key)) {
if(db[key].indexOf(',')>-1){
console.log(key+' | ' + db[key]);
}
}
}
As you can see I can retrieve these values
batch_number | test,b
temp | ,,67,6,87,86,5,67865,876,67
integrity | ,,,,,,,,,,,,,,,,,,,,,,,
weight | 760,765,755,758,759,758,758,769,758,762,759,7
Now I would like to know how if there is a way I can retrieve only the keys of values that do not have commas
Upvotes: 1
Views: 107
Reputation: 41
Change indexOf(',') > -1
to indexOf(',') == -1
:
var db = {
"name": "Nkosana",
"middle": "Baryy",
"surname": "walked",
"batch_number": "test,b",
"temp": ",,67,6,87,86,5,67865,876,67",
"integrity": ",,,,,,,,,,,,,,,,,,,,,,,",
"weight": "760,765,755,758,759,758,758,769,758,762,759,7",
"comment": "oh la la",
};
for (var key in db) {
if (db.hasOwnProperty(key)) {
if(db[key].indexOf(',')==-1){
console.log(key+' | ' + db[key]);
}
}
}
Upvotes: 3
Reputation: 1978
Simply change if(db[key].indexOf(',')>-1)
to if(db[key].indexOf(',') == -1)
.
Here's your updated code:
var db = {
"name": "Nkosana",
"middle": "Baryy",
"surname": "walked",
"batch_number": "test,b",
"temp": ",,67,6,87,86,5,67865,876,67",
"integrity": ",,,,,,,,,,,,,,,,,,,,,,,",
"weight": "760,765,755,758,759,758,758,769,758,762,759,7",
"comment": "oh la la",
};
for (var key in db) {
if (db.hasOwnProperty(key)) {
if(db[key].indexOf(',') == -1){
console.log(key+' | ' + db[key]);
}
}
}
Upvotes: 2
Reputation: 7161
Try this:
var db = {
"name": "Nkosana",
"middle": "Baryy",
"surname": "walked",
"batch_number": "test,b",
"temp": ",,67,6,87,86,5,67865,876,67",
"integrity": ",,,,,,,,,,,,,,,,,,,,,,,",
"weight": "760,765,755,758,759,758,758,769,758,762,759,7",
"comment": "oh la la",
};
for (var key in db) {
if (db.hasOwnProperty(key)) {
if(db[key].indexOf(',')==-1){
console.log(key+' | ' + db[key]);
}
}
}
Upvotes: 2
Reputation: 402553
As I mentioned in my comment, the fix is simple. You just need to change the if condition a bit:
if(db[key].indexOf(',')==-1){ ... }
This is because indexOf
returns -1 when the search string is not present in the string to be searched.
The complete code listing is:
var db = {
"name": "Nkosana",
"middle": "Baryy",
"surname": "walked",
"batch_number": "test,b",
"temp": ",,67,6,87,86,5,67865,876,67",
"integrity": ",,,,,,,,,,,,,,,,,,,,,,,",
"weight": "760,765,755,758,759,758,758,769,758,762,759,7",
"comment": "oh la la",
};
for (var key in db) {
if (db.hasOwnProperty(key)) {
if(db[key].indexOf(',') == -1){
console.log(key+' | ' + db[key]);
}
}
}
Upvotes: 1