How to fix field name is undefined error?

604
December 26, 2016, at 03:06 AM

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 ?

Answer 1

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.

Answer 2

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.

Rent Charter Buses Company
READ ALSO
Tag mismatch error in AES-256-GCM Decryption using Java

Tag mismatch error in AES-256-GCM Decryption using Java

I have the following function written in Javascript for encryption using aes-256-gcm:

2544
SCRIPT438 Error in Internet Explorer 11

SCRIPT438 Error in Internet Explorer 11

I've been working on JavaScript lately, and everything was fine until I opened my page in IE11as per Mozilla website

904
Load image from file in Javascript

Load image from file in Javascript

So I have my Javascript code that I've included in my HTML file:

1007
random background image on blogger

random background image on blogger

I'm trying to pull together some kind of code that will randomize the background image on my blogger blog

518