I have this Javascript code to sort strings but I get error a.k is undefined
var dataset = [{
"field1": "dfg34r",
"field2": "sdfsd"
}, {
"field1": "d3f32dg",
"field2": "fgjfgj"
}, {
"field1": "fdbhjjts",
"field2": "hswer"
}, {
"field1": "dfg4r",
"field2": "ghje"
}, {
"field1": "fgsdfwe",
"field2": "dhfke"
}];
function sort_col(evt){
var k = evt.target.innerText; //k = clicked field name field1 or field2
dataset.sort(function (a, b) {
var nameA = a.k.toUpperCase(); // error here a.k is undefined
var nameB = b.k.toUpperCase();
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
});
}
if I removed toUpperCase
the code work normally so how I can fix this error and be able to convert string to upper case ?
You have to use bracket notation
at this context instead of a dot notation,
var nameA = a[k]toUpperCase();
var nameB = b[k]toUpperCase();
If you use dot notation
, then property look up over objects a
and b
will happen for the property k
, not the value which resides inside that.
I think modifying the code like below should solve the undefined problem.
function sort_col(evt){
var k = evt.target.innerText; //k = clicked field name field1 or field2
dataset.sort(function (a, b) {
var nameA = "";
var nameB = "";
if(k=="field1"){
nameA = a.field1.toUpperCase(); // error here a.k is undefined
nameB = b.field1.toUpperCase();
} else{
nameA = a.field2.toUpperCase(); // error here a.k is undefined
nameB = b.field2.toUpperCase();
}
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
});
}
It is giving undefined for a.k as it will not be able to replace the value of k dynamically during the a.k.toUpperCase evaluation.
Firebase Cloud Functions: PubSub, "res.on is not a function"
TypeError: Cannot read properties of undefined (reading 'createMessageComponentCollector')
I have the following function written in Javascript for encryption using aes-256-gcm:
I've been working on JavaScript lately, and everything was fine until I opened my page in IE11as per Mozilla website
So I have my Javascript code that I've included in my HTML file:
I'm trying to pull together some kind of code that will randomize the background image on my blogger blog