Eliminate quotation marks from an array in order to function as a function with a variable

I receive an array from a JSON object. I then need to loop through the array because it contains function names that I want to execute.

The following code snippet works when entered manually:

var view_functions = [
    header,
    footer
];

for (i = 0; i < view_functions.length; i++) {

    view_functions[i]();             
}

However, in reality, the view_functions variable should be populated dynamically from the JSON data, rather than hard-coded. The JSON structure is as follows, containing an array of function names with quotes around them:

"functions" : ["header","footer"]

So, when extracting the JSON data, it is presented as an array with quotes around each element. How can I convert this structure into a usable view_functions variable without the quotes?

Thank you for your help!

Answer №1

Consider giving this a shot:

    let user_functions = your_json_object.methods; // ["navigation", "sidebar"]

    for (let method of user_functions) {

        window[method]();             
    }

Answer №2

To clarify, it's important to note that a JSON "object" doesn't actually exist; JSON is strictly a string format.

If you opt to store your functions within a placeholder object (referred to as a "dummy" object in this example), you can then easily access properties that correspond to the names listed in an array.

var view_functions = { "functions" : ["header", "footer"] };

var dummy = {
    header: function(){ console.log("header"); },
    footer: function(){ console.log("footer"); }
};

// Iterate through the strings in the array and call the function
// associated with the corresponding key in the dummy object:
view_functions.functions.forEach(function(f){
   dummy[f]();
});

Answer №3

To determine whether the functions are in the global scope, you can utilize this approach:

window[view_functions[i]]();

Note that globally defined functions are essentially methods of the global window object, making them accessible through bracket notation window[...]. By employing bracket notation instead of using eval, you avoid potential risks.

If the functions belong to an object, simply substitute window with the object's name.

It is advisable to verify the existence of the function before calling it:

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]]();
  }
};

Answer №4

To loop through the array, you can use Array.prototype.forEach() and access functions within the Global context using either the keyword window or this.

Check out this code snippet that uses this[fn]():

function printHeader() {
  console.log("Printing header");
}

function printFooter() {
  console.log("Printing footer");
}

const pageFunctions = { 
  "functions": ["printHeader", "printFooter"] 
};

pageFunctions.functions.forEach(fn => this[fn]());

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing CSS styles according to user preferences. Switching between dark mode and light mode based on subscription

Is there a way to dynamically change CSS property values based on user interaction, such as toggling between dark mode and light mode? I am currently exploring the option of setting up a subscription to track these changes, but I want to know how I can act ...

Retrieving Django view information using AJAX

Currently, I am in the process of developing an application that updates the main page's data via AJAX. After reading through a helpful response on this Stackoverflow post, I implemented AJAX to refresh my page. In addition to this, I have a specific ...

What is the method for sending arguments to material avatar using require?

import Avatar from '@material-ui/core/Avatar'; Here is an example of working code: <Avatar alt="user 4" src={require('Assets/img/user-1.jpg')} className="size-80 rounded-circle border-info rct-notify" /> However, I encountered ...

Python script for converting log.txt file to JSON

Currently in the process of learning Python with a limited programming background, I have taken on a challenging project. The task at hand involves converting a system log stored in a .txt file into JSON format. The ultimate goal is to create a Python pro ...

The property 'label' is not found in the 'string' type in Typescript

Below is the code snippet I am using: interface State { resourceGroup: QuickPickItem | string; } setEvent(state.resourceGroup?.label).catch(err => console.error(err)); When executing this code, I encountered the following error messa ...

Leveraging JavaScript functions for invoking Ajax requests, accompanied by ASP.NET controls

Having a background in PHP, I am accustomed to using a PHP file to handle all of my ajax calls. Recently, I have been introduced to ASP.NET controls and the overall environment. I am curious about the correct method for handling ajax requests when they n ...

What is the best way to store multiple checkbox categories as an array in a JSON object within a React application

Currently, I am in the process of creating a page that allows users to create posts and select multiple categories. However, I have encountered an issue when sending data via a post request that involves multiple category objects. It seems that I am strugg ...

Validating User Input for Java Arrays

Welcome to the Monkey Business Challenge! I'm a novice Java student embarking on a project to create a basic Java console application for tracking the food consumption of a family of four monkeys. Here are the key requirements: - Utilize a 2-dimensi ...

Using a `foreach` loop in PHP to organize data into groups

I am facing a challenge with two JSON files. One file contains information about leagues, including league id and league name, while the other file has details about fixtures, including fixture id and league id. My goal is to loop through the fixtures, gro ...

Why are uppercase letters not allowed in field names for Amazon CloudSearch?

We are currently looking into sending our company's JSON data to Amazon Cloud search for indexing. Initially, we thought it would be a simple task of transferring the data as it is. However, we discovered that our attribute names are in camelCase form ...

Clear the input field value when the onClick event occurs, and retain the value if not changed

When I initially set a default value in the input field, it is important that this value is removed when clicked inside the field. However, if the inserted value is left blank and the mouse cursor moves away from the field, the default value must be restor ...

My ability to click() a button is working fine, but I am unable to view the innerHTML/length. What could be the issue? (NodeJS

Initially, my goal is to verify the existence of the modal and then proceed by clicking "continue". However, I am facing an issue where I can click continue without successfully determining if the modal exists in the first place. This occurs because when I ...

Facing an issue with the GPT-3.5 Turbo post request functionality in a Node.js application

I am attempting to receive a JSON response when making a POST request to an API. The current outcome I am getting is: { "success" : true }, and the prompt object looks like this: { "prompt" : "anorexia nervosa restricting type ...

What is the significance of combining two arrays?

const customTheme = createMuiTheme({ margin: value => [0, 4, 8, 16, 32, 64][value], }); customTheme.margin(2); // = 8 This code snippet showcases how to define spacing values in a Material-UI theme configuration. For more details on customization re ...

Display the designated element upon clicking the designated link exclusively

I'm working with this specific HTML setup: <a href="#" class="dp">Click me</a> <div class="dp_div" style="display: none;"> this is the content within the div </div> My goal is to display the hidden div with a class of "dp_ ...

Automate the process of adding or removing a class created by material ui through programming

Is there a way to dynamically manage the material-UI classes I declared in makeStyles()? Below is the code snippet: import React from 'react'; import { DropboxIcon, GoogleDriveIcon, BoxIcon } from '../components/icons'; import { makeSt ...

"Implementing Notifications in Mongoose: A Step-by-Step Guide

My current user schema is set up as follows: const Schema = mongoose.Schema; const bcrypt = require("bcryptjs"); const userSchema = new Schema( { email: { type: String, required: true, index: { unique: true } }, ...

Choosing the appropriate data type for form data on the server

Seeking assistance on uploading an audio file to my server using the following method: var fd = new FormData(); fd.append('fname', 'test.wav'); fd.append('data', soundBlob); $.ajax({ type: 'POST', url: &apos ...

Retrieve an array field across various documents and combine the elements to form a single object

Consider a scenario where there is a users collection. Each user document includes an array of posts called posts. The goal is to query this collection as follows: Retrieve 2 posts, starting at index Nstart and ending at index Nend, from each user in the ...

Determine the specified keys within a JSON object using Python

My goal is to generate JSON output that includes a list of MAC addresses and corresponding timestamps for each address. Here's an example of the desired output: [ "B2:C7:23:10:A0": [ "2014-04-04T21:30:46.348900800Z", "2014-04-04T21:30:46.348 ...