Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery push the key and value into array

Tags:

jquery

I have the initial array in the following way:

var bankNamesList = [{
    'BARODA': 'BARODA'
}, {
    '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>';
$('.submenu-bank-list').html(bankNames);

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

i tried in the following way, but no luck.

var nameAttr = 'SBI';    
bankNamesList.push({nameAttr:nameAttr});
like image 454
vishnu Avatar asked May 25 '15 09:05

vishnu


2 Answers

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';    
bankNamesList.push({nameAttr:nameAttr});

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;
bankNamesList.push(item);
like image 130
Michael Geary Avatar answered Sep 20 '22 14:09

Michael Geary


You just need quotes around key:

var nameAttr = 'SBI';
bankNamesList.push({
    'nameAttr': nameAttr
});
like image 26
Tushar Avatar answered Sep 20 '22 14:09

Tushar