Search code examples
javascriptjqueryjsonhandlebars.jshandlebarshelper

handlebarsjs - Can I access element by json key?


I have json like this:

"elements":[

{
"type":"AAAA",
"val":{"detail":"111"}},

"type":"BBBB",
"val":{"detail":"222"}}
}]

How can I get value detail for element with specific type? I can probably make a each loop, but is there any more efficient way, like in XSL:

{{elements.type['AAAA'].val}} 

Solution

  • In plain Javascript, you can write a helper function for it.

    function getReference(array, key) {
        var r;
        array.some(function (a) {
            if (a.type === key) {
                r = a;
                return true;
            }
        });
        return r;
    }
    
    var object = { "elements": [{ "type": "AAAA", "val": { "detail": "111" } }, { "type": "BBBB", "val": { "detail": "222" } }] };
    
    document.write('<pre>' + JSON.stringify(getReference(object.elements, 'AAAA').val, 0, 4) + '</pre>');