2
var elems = [];
var at1 = $(indx).attr('class'); //or any string
var at2 = $(indx).html(); //or any string
elems.push({
  at1: at2
});

The output I get is: this Why can not I set the key as a string?

admix
  • 1,752
  • 3
  • 22
  • 27

1 Answers1

4

The way you create an object, the key is going to be interpreted literally as "at1" string. In your case you need to do it slightly more verbose:

var at1 = $(indx).attr('class');
var at2 = $(indx).html();

var obj = {};
obj[at1] = at2;

elems.push(obj);

... or using ES2015 computed property name:

var at1 = $(indx).attr('class');
var at2 = $(indx).html();

elems.push({
  [at1]: at2
});
dfsq
  • 191,768
  • 25
  • 236
  • 258