Search code examples
jqueryarraysjsoneachstartswith

Using jQuery Attribute Starts With Selector in Each Loop


I'm retrieving a localstorage string that started life as JSON:

[
    {
        "Key01": "Val01",
        "Key02": "Val02",
        "Key03": "Val03",
        "KeyInfo1": [
            {
                "KIName": "KIVal01",
                "KIId": "KIVal02"
            }
        ],
        "KeyInfo2": [
            {
                "KIName": "KIVal03",
                "KIId": "KIVal04"
            }
        ],
        "KeyInfo3": [
            {
                "KIName": "KIVal05",
                "KIId": "KIVal06"
            }
        ]
    }
]

and converting it back into a JSON array:

var stuff = localStorage.getItem("ls");
var testparse = $.parseJSON(stuff);

I'd like to be able to run a jQuery $.each() loop to isolate only the arrays whose names begin with 'KeyInfo' and tease out their data. I've used jQuery's "Attribute Starts With Selector" feature on HTML elements which have ready selectors like IDs or form names, e.g.: input[name^='news']. Are there such selectors available from JSON? A loop like:

$.each(testparse[0]."[key^='KeyInfo']"[0], function(key, value){
        console.log(key + ' = ' + value);
    });

understandably throws a Uncaught SyntaxError: Unexpected string since I'm trying to access a key before I've set itself up as an attribute in the function associated with the $.each() loop. Can such a scenario work? If not, can someone recommend a way to isolate just those arrays beginning with "KeyInfo"?


Solution

  • You can do a simple check against each key to see if they start with 'KeyInfo'.

    $.each(testparse[0], function(key, value){
        if (key.indexOf('KeyInfo') === 0) {
            console.log(key + ' = ' + value);
        }
    });