How to push both key and value into an Array in Jquery

KillerFish picture KillerFish · Jan 28, 2011 · Viewed 501.5k times · Source

I am reading RSS feed and pushing both Title and Link into an Array in Jquery.

What i did is

var arr = [];

            $.getJSON("displayjson.php",function(data){
                $.each(data.news, function(i,news){
                    var title = news.title;
                    var link = news.link;
                    arr.push({title : link});
                });                      
            });

And i am reading that array again using

$('#show').click(function(){
                $.each(arr, function(index, value){
                    alert( index +' : '+value);
                });
            });

But it Giving me Output as

1:[Object Object]
2:[Object Object]
3:[Object Object]

like this ...

How i can get both tile and link as a pair ( title as key and link as value)

Answer

Tomalak picture Tomalak · Jan 28, 2011

There are no keys in JavaScript arrays. Use objects for that purpose.

var obj = {};

$.getJSON("displayjson.php",function (data) {
    $.each(data.news, function (i, news) {
        obj[news.title] = news.link;
    });                      
});

// later:
$.each(obj, function (index, value) {
    alert( index + ' : ' + value );
});

In JavaScript, objects fulfill the role of associative arrays. Be aware that objects do not have a defined "sort order" when iterating them (see below).

However, In your case it is not really clear to me why you transfer data from the original object (data.news) at all. Why do you not simply pass a reference to that object around?


You can combine objects and arrays to achieve predictable iteration and key/value behavior:

var arr = [];

$.getJSON("displayjson.php",function (data) {
    $.each(data.news, function (i, news) {
        arr.push({
            title: news.title, 
            link:  news.link
        });
    });                      
});

// later:
$.each(arr, function (index, value) {
    alert( value.title + ' : ' + value.link );
});