簡體   English   中英

JSON object -> 陣列? 我應該如何轉換它?

[英]JSON object -> array? how should I convert it?

拿兩個:) 我有一個 jquery 的自動完成 texbox,點擊一個按鈕,我需要檢查輸入的值是來自自動完成還是一個全新的值。

問題是“緩存”是某種 JSON 對象數組,但為了能夠使用if ( input in cache ) {... }我需要將其轉換為簡單的 javascript 數組。 最好的方法是什么?

PS FireBug 說 'cache=[object Object]'

//////////////////////////////////////////// autocomplete code //////////////////
    var cache = {},
        lastXhr;
    $( "#inputV" ).autocomplete({
        minLength: 2,
        source: function( request, response ) {
            var term = request.term;
            if ( term in cache ) {
                response( cache[ term ] );
                return;
            }

            lastXhr = $.getJSON( "search.php", request, function( data, status, xhr ) {
                cache[ term ] = data;
                if ( xhr === lastXhr ) {
                    response( data );
                }
            });
        }
    });


////////////////////////// check if input comes from autocomplete  //////////////////
    $('#btn_check').click(function()        {

        var input = $("#inputV").val();
        alert(input);

        console.log('cache='+cache); 
        /// FireBug says 'cache=[object Object]'

        if ( input in cache ) 
            {
                alert("yes");
             }  
            else
            {
                alert("no");
            }   
    });

這是一個響應的樣子。

[
    {
        "id": "Podiceps nigricollis",
        "label": "Black-necked Grebe",
        "value": "Black-necked Grebe"
    },
    {
        "id": "Nycticorax nycticorax",
        "label": "Black-crowned Night Heron",
        "value": "Black-crowned Night Heron"
    },
    {
        "id": "Tetrao tetrix",
        "label": "Black Grouse",
        "value": "Black Grouse"
    },
    {
        "id": "Limosa limosa",
        "label": "Black-tailed Godwit",
        "value": "Black-tailed Godwit"
    },
    {
            "id": "Chlidonias niger",
        "label": "Black Tern",
        "value": "Black Tern"
    },
    {
        "id": "Larus marinus",
        "label": "Great Black-backed Gull",
        "value": "Great Black-backed Gull"
    },
    {
        "id": "Larus fuscus",
        "label": "Lesser Black-backed Gull",
        "value": "Lesser Black-backed Gull"
    },
    {
        "id": "Larus ridibundus",
        "label": "Black-headed Gull",
        "value": "Black-headed Gull"
    },
    {
        "id": "Turdus merula",
        "label": "Common Blackbird",
        "value": "Common Blackbird"
    },
    {
        "id": "Sylvia atricapilla",
        "label": "Blackcap",
        "value": "Blackcap"
    },
    {
        "id": "Rissa tridactyla",
        "label": "Black-legged Kittiwake",
        "value": "Black-legged Kittiwake"
    },
    {
        "id": "Aegypius monachus",
        "label": "Eurasian Black Vulture",
        "value": "Eurasian Black Vulture"
    }
]

(替代答案,我並不是說最后一個是CW。)

問題是“緩存”是某種 JSON 對象數組

實際上,它不是一個數組。 這是一個 object。 (它是通過var cache = {};創建的,我們可以這樣判斷。)

...但是為了能夠使用if ( input in cache ) {... }我需要將它轉換為一個簡單的 javascript 數組。

實際上,沒有。 此上下文中的in運算符測試 object 是否包含具有您給它的名稱的屬性。 例子:

var obj = {foo: 1};  // An object with a property called "foo"
alert('foo' in obj); // alerts true, `obj` has a "foo" property
alert('bar' in obj); // alerts false, there is no "bar" property in `obj`

請注意, in運算符的左側必須是字符串(它可以是文字,如上所述,也可以是任何導致字符串的表達式,例如變量引用)。

click處理程序中的代碼獲取“inputV”字段的值,並查看該值是否是cache object 中的屬性名稱。

您可能想檢查它是否是cache object 的屬性之一的 如果是這樣:

$('#btn_check').click(function()        {

    var input = $("#inputV").val();
    var found, propName;

    alert(input);

    console.log('cache='+cache); 
    /// FireBug says 'cache=[object Object]'

    found = false;
    for (propName in cache ) {
        if (cache[propName] == input) {
            found = true;
            break;
        }
    }
    alert(found);
});

由於我們知道cache是一個無聊的舊 object(事實上它是使用var cache = {};創建的),我們可以非常安全地使用上面的原始for..in循環。 但是如果你想更加小心,你可以使用hasOwnProperty來確保你只檢查了cache有自己副本的屬性(而不是它從原型繼承的屬性):

    for (propName in cache ) {
        if (cache.hasOwnProperty(propName) && cache[propName] == input) {
            found = true;
            break;
        }
    }

不過,在這種情況下,這也不是必需的,因為我們知道cache是一個普通的 object,並且禁止有人做一些非常愚蠢的事情,比如擴展Object.prototype (你不應該這樣做),它的所有可枚舉屬性(the things for..in枚舉)是它自己的屬性。

如果沒有看到 JSON 的外觀,很難判斷。 您可以將if ( input in cache )替換為if(cache.hasOwnProperty(input))而不必費心將其轉換為數組,但這取決於緩存 object 包含的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM