I'm currently struggling with a JavaScript problem. I want to return a multi-level property, as well as every variable contained within, by passing in the original object, and an array of paths to the properties I want.
For example, if I have the following object:
obj = {
product: {
candidate: {
id: 10,
reference: "test",
count: 4,
steps: 10
}
}
}
I want to be able to call a method:
getVarPath(obj, ["product.candidate.ID", "product.candidate.reference"])
And then have it return one object with each variable passed in the array, in it's original structure. So this would return an object looking like so:
{
product: {
candidate: {
id: 10,
reference: "test"
}
}
}
I do have this working in my local solution at the moment (passing in one string rather than an array at the moment).
The solution at the moment is pretty horrid but I'm looking to improve it, so if anyone can think of a better method that would be great. Again, this is pretty horrid right now but I'm looking to improve it. But it does the job:
var getVarPath = function(obj, keys){
var elements = keys.split("."),
evalStr = "",
objStr = "obj",
newObjStr = "newObj",
newObj = {};
if(elements.length > 1){
elements.forEach(function(key, index){
// first append a property accessor at the end of the eval string
evalStr = evalStr + "['" + key + "']";
// if we're at the last element, we've reached the value, so assign it
if(index === elements.length -1){
eval(newObjStr + evalStr + " = " + objStr + evalStr);
}
else {
// if we're not at the last, we're at an object level
// if the nested object doesn't exist yet, create it
if(!eval(newObjStr + evalStr)){
eval(newObjStr + evalStr + " = {};");
}
}
});
}
return newObj;
}