5

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});

3 Answers 3

10

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Nice answer.+1 (useful for me)
4

You just need quotes around key:

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

1 Comment

That does the same thing as the original code at the end of the question. {foo:bar} and {'foo':bar} are no different from each other: they both create an object with a single property named foo whose value comes from the variable bar.
2

Try This

 var anser_array = [];
 var KeyValuePair = '{"Qid"' + ":" + Question_id + "," + "Ans" + ":" + answer_id + "}";
 anser_array.push(KeyValuePair);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.