vishnu vishnu - 2 months ago 7
jQuery Question

jquery push the key and value into array

I have the initial array in the following way:

var bankNamesList = [{
}, {
'AB': 'AB'

Then i am looping the values and appended to main variable and constructing a drop-down

var bankNames = '<ul class="root" id="exp-bank-names">';
$.each(bankNamesList, function() {
$.each(this, function(name, value) {
bankNames += '<li><a href="#" name="' + name + '">' + value + '</a></li>';
bankNames += '</ul>';

How do i push the new value in to an array.

i tried in the following way, but no luck.

var nameAttr = 'SBI';

Answer Source

When you create an object and its properties using an object literal, the name to the left of the : is taken literally (pun intended). It doesn't look up a variable name, it uses the text you actually write.

So your example at the end:

var nameAttr = 'SBI';    

is actually the same as if you'd written this:

bankNamesList.push({ 'nameAttr': 'SBI' });

It looks like you probably meant it to do this, similar to the other elements of the bankNamesList array:

bankNamesList.push({ 'SBI': 'SBI' });

You could do that this way:

var nameAttr = 'SBI';
var item = {};
item[nameAttr] = nameAttr;