plusz
plusz

Reputation: 233

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

Upvotes: 0

Views: 36

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386578

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

Upvotes: 1

Related Questions