简体   繁体   中英

Pass an undetermined number of object properties that may be nested

I'm trying to write a handlebars helper where I can pass a JSON string that needs to be parsed, and then grab any specific property, not knowing how many levels of nesting there may be, for example:

Handlebars.registerHelper 'parseJSON', (string, properties) ->
    json = JSON.parse string
    # how can I do: return json[oneProperty][andANestedProperty]

then with 'responseBody' as my JSON string, not sure how to pass it in, but the idea is I have something like:

{{parseJSON responseBody [oneProperty][andANestedProperty] }}

If you want to be able to say things like:

{{parseJSON json 'p1' 'p2'}}
{{parseJSON json 'p1' 'p2' 'p3'}}

in your template then you just need to make your helper accept any number of arguments. The only tricky thing is that the Handlebars properties argument is always last. This is actually pretty easy using a CoffeeScript splat :

Handlebars.registerHelper 'parseJSON', (json, path..., properties) ->
    # path will be an array in here

That will give you things like ['p1', 'p2'] and ['p1', 'p2', 'p3'] in the path array inside your helper.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM