Consider this javascript:
var values = {
name: "Joe Smith",
location: {
city: "Los Angeles",
state: "California"
}
}
var string = "{name} is currently in {location.city}, {location.state}";
var out = string.replace(/{([\w\.]+)}/g, function(wholematch,firstmatch) {
return typeof values[firstmatch] !== 'undefined' ?
values[firstmatch] : wholematch;
});
This will output the following:
Joe Smith is currently in {location.city}, {location.state}
But I want to output the following:
Joe Smith is currently in Los Angeles, California
I'm looking for a good way to convert multiple levels of dot notation found between braces in the string into multiple parameters to be used with bracket notation, like this:
values[first][second][third][etc]
Essentially, for this example, I'm trying to figure out what regex string and function I would need to end up with the equivalent of:
out = values[name] + " is currently in " + values["location"]["city"] +
values["location"]["state"];
NOTE: I'd like to do this without using eval()
.
Using a helper function to iteratively access the properties:
function getNestedValue(obj, prop) {
var value, props = prop.split('.'); // split property names
for (var i = 0; i < props.length; i++) {
if (typeof obj != "undefined") {
obj = obj[props[i]]; // go next level
}
}
return obj;
}
var string = "{name} is currently in {location.city}, {location.state}";
var out = string.replace(/{([^}]+)}/g, function(wholematch,firstmatch) {
var value = getNestedValue(joe, firstmatch);
return typeof value !== 'undefined' ? value : wholematch;
});
// "Joe Smith is currently in Los Angeles, California"
Try the above example here.
Edit: Something slightly elegant, using the Array.prototype.reduce
method, part of the new ECMAScript 5th Edition Standard:
function replace(str, obj) {
return str.replace(/{([^}]+)}/g, function(wholematch,firstmatch) {
var value = firstmatch.split('.').reduce(function (a, b) {
return a[b];
}, obj);
return typeof value !== 'undefined' ? value : wholematch;
});
}
replace("{name} is currently in {location.city}, {location.state}", values);
// "Joe Smith is currently in Los Angeles, California"
Try the new example here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With