Ox.formatString: support '{a.b.c}' access to nested object properties
This commit is contained in:
parent
42760324f3
commit
f34d70fd4c
1 changed files with 13 additions and 1 deletions
|
@ -682,10 +682,22 @@ Ox.formatString <f> Basic string formatting
|
||||||
'foobar'
|
'foobar'
|
||||||
> Ox.formatString('{a}{b}', {a: 'foo', b: 'bar'})
|
> Ox.formatString('{a}{b}', {a: 'foo', b: 'bar'})
|
||||||
'foobar'
|
'foobar'
|
||||||
|
> Ox.formatString('{a.x}{a.y}', {a: {x: 'foo', y: 'bar'}})
|
||||||
|
'foobar'
|
||||||
|
> Ox.formatString('{a\\.b}', {'a.b': 'foobar'})
|
||||||
|
'foobar'
|
||||||
@*/
|
@*/
|
||||||
Ox.formatString = function(string, collection) {
|
Ox.formatString = function(string, collection) {
|
||||||
return string.replace(/\{([^}]+)\}/g, function(string, match) {
|
return string.replace(/\{([^}]+)\}/g, function(string, match) {
|
||||||
return collection[match];
|
// make sure to not split at escaped dots ('\.')
|
||||||
|
var keys = match.replace(/\\\./g, '\n').split('.').map(function(key) {
|
||||||
|
return key.replace(/\n/g, '.')
|
||||||
|
}),
|
||||||
|
value = collection;
|
||||||
|
while (keys.length) {
|
||||||
|
value = value[keys.shift()];
|
||||||
|
}
|
||||||
|
return value;
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue