Reputation: 23
I get an array from a JSON object. Then I want to iterate over that array because they are function names, and I want them to run.
The following will work if I manually do it.
var view_functions = [
header,
footer
];
for (i = 0; i < view_functions.length; i++) {
view_functions[i]();
}
But the view_functions variable is supposed to come from the JSON, and not done manually. The JSON part looks like the following, which is an array.
"functions" : ["header","footer"]
So when I grab the JSON it is an array with quotes around it. How do I make this like the working view_functions var without quotes?
Thanks!
Upvotes: 0
Views: 56
Reputation: 13304
Depends: if the functions are in the global scope you can do:
window[view_functions[i]]();
Remember that all globally defined functions are in fact methods of the global window object. So they can be accessed by using bracket notation window[...]
. So to avoid using eval
you can use the bracket notation.
If they are a method of an object you can replace window
with the object.
It would be a good idea to check if the function exists:
Object.prototype.toString(window[view_functions[i]]) === "[object Function]"
var funcObj = JSON.parse("{\"functions\" : [\"header\" , \"footer\"]}");
header = function() {
console.log("test header");
}
footer = function() {
console.log("test footer");
}
for (var i = 0; i < funcObj.functions.length; i++) {
if (Object.prototype.toString.call(window[funcObj.functions[i]]) === "[object Function]") {
window[funcObj.functions[i]]();
}
};
Upvotes: 0
Reputation: 19070
You can iterate the array with Array.prototype.forEach() and access to the functions that are in the Global context using the keyword window
or this
.
Code example using this[fn]()
:
function header () {
console.log("function header");
}
function footer () {
console.log("function footer");
}
const view_functions = {
"functions": ["header" , "footer"]
};
view_functions.functions.forEach(fn => this[fn]());
Upvotes: 0
Reputation: 65796
First, there is no such thing as a JSON "object". JSON is a string format.
If you store your functions in a "dummy" object (just for scope), you can then access property names that match the names in the array.
var view_functions = { "functions" : ["header" , "footer"] };
var dummy = {
header: function(){ console.log("header"); },
footer: function(){ console.log("footer"); }
};
// Loop over the strings in the array and invoke the function
// with the matching key in the dummy object:
view_functions.functions.forEach(function(f){
dummy[f]();
});
Upvotes: 1
Reputation: 2986
Maybe you can try this:
var view_functions = you_json_obj.functions; // ["header", "footer"]
for (let fn of view_functions) {
window[fn]();
}
Upvotes: 1