Programing

Jquery의 배열에 키와 값을 모두 푸시하는 방법

lottogame 2020. 10. 9. 08:43
반응형

Jquery의 배열에 키와 값을 모두 푸시하는 방법


RSS 피드를 읽고 Title과 Link를 Jquery 의 Array에 넣습니다 .

내가 한 일은

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

그리고 나는 그 배열을 다시 읽고 있습니다.

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

그러나 그것은 나에게 출력 을 제공합니다.

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

이렇게 ...

타일링크 를 쌍으로 얻는 방법 ( 제목을 키로, 링크를 값으로 )


JavaScript 배열에는 키가 없습니다. 그 목적을 위해 개체를 사용하십시오.

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

JavaScript에서 객체는 연관 배열의 역할을 수행합니다. 개체를 반복 할 때 개체에는 정의 된 "정렬 순서"가 없습니다 (아래 참조).

그러나 귀하의 경우에는 원래 객체 ( data.news)에서 데이터를 전송하는 이유가 전혀 명확하지 않습니다 . 왜 단순히 객체에 대한 참조를 전달하지 않습니까?


객체와 배열을 결합하여 예측 가능한 반복 키 / 값 동작 을 달성 할 수 있습니다.

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

이 코드

var title = news.title;
var link = news.link;
arr.push({title : link});

당신이 생각하는대로하지 않습니다. 푸시되는 것은 "title"이라는 단일 멤버가있는 새 개체이며 link값으로 ... 실제 title값은 사용되지 않습니다. 두 개의 필드가있는 개체를 저장하려면 다음과 같이해야합니다.

arr.push({title:title, link:link});

또는 최근 Javascript 발전으로 바로 가기를 사용할 수 있습니다.

arr.push({title, link}); // Note: comma "," and not colon ":"

파이썬 튜플에 가장 가까운 것은 대신

arr.push([title, link]);

Once you have your objects or arrays in the arr array you can get the values either as value.title and value.link or, in case of the pushed array version, as value[0], value[1].


I think you need to define an object and then push in array

var obj = {};
obj[name] = val;
ary.push(obj);

arr[title] = link;

You're not pushing into the array, you're setting the element with the key title to the value link. As such your array should be an object.


You might mean this:

var unEnumeratedArray = [];
var wtfObject = {
                 key    : 'val', 
                 0      : (undefined = 'Look, I\'m defined'),
                 'new'  : 'keyword', 
                 '{!}'  : 'use bracket syntax',
                 '        ': '8 spaces'
                };

for(var key in wtfObject){
    unEnumeratedArray[key] = wtfObject[key];
}
console.log('HAS KEYS PER VALUE NOW:', unEnumeratedArray, unEnumeratedArray[0], 
             unEnumeratedArray.key, unEnumeratedArray['new'], 
             unEnumeratedArray['{!}'], unEnumeratedArray['        ']);

You can set an enumerable for an Object like: ({})[0] = 'txt'; and you can set a key for an Array like: ([])['myKey'] = 'myVal';

Hope this helps :)

참고URL : https://stackoverflow.com/questions/4825899/how-to-push-both-key-and-value-into-an-array-in-jquery

반응형