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

后端 未结 5 2284
[愿得一人]
[愿得一人] 2020-12-12 11:45

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

What i did is

var arr = [];

               


        
5条回答
  •  抹茶落季
    2020-12-12 12:28

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

提交回复
热议问题