Skip to content

Instantly share code, notes, and snippets.

@saintsGrad15
Last active March 17, 2016 16:16
Show Gist options
  • Save saintsGrad15/5ebd6063185ad0dd4c81 to your computer and use it in GitHub Desktop.
Save saintsGrad15/5ebd6063185ad0dd4c81 to your computer and use it in GitHub Desktop.
Convert a dot notated object path to a square bracket notated object path
/**
* Takes a dot notated object string ("root.child1.child2.child3") and converts it to square bracket notation ("root[child1][child2][child3]").
*
* @param dot_string {string}
* A string in dot notation.
* * Must be of a non-zero length
* * Must include at least one "."
* * Must have more than one token
*
* @param include_single_quotes {boolean}
* A flag to indicate if each attribute selector between square brackets should be single-quoted
* * Must be a boolean
* * Defaults to false
*/
var convert_dot_to_bracket = function(dot_string, include_single_quotes)
{
// dot_string is defined, a String, not empty and contains at least one "."
if (typeof dot_string !== "undefined" && dot_string.constructor.name == "String" && dot_string.length > 0 && dot_string.indexOf(".") >= 0)
{
var token_list = dot_string.split(".");
token_list = token_list.filter(function(thisArg){ return thisArg !== "" }); // Remove all empty strings from the array
// There is at least one root and one attribute token
if (token_list.length > 1)
{
var root = token_list.splice(0,1); // pop the first element into <root>
var single_quote_place_holder = ""; // Create an empty string. It will only become useful if <include_single_quotes> is truthy
var out = "" + root; // Create the output string and start it with <root>
// If <include_single_quotes> is truthy set it to "'" otherwise leave it ""
if (include_single_quotes)
single_quote_place_holder = "'";
token_list.forEach(function(currentValue, index, array)
{
out += "[" + single_quote_place_holder + currentValue + single_quote_place_holder + "]"; // Append the formatted token to <out>
});
return out;
}
else // There is only one token
{
return "";
}
}
else // dot_string is invalid
{
return "";
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment