utilizing eval() in order to retrieve a pointer to an include

I am currently developing a form widget where the form schema is fetched from an API and generated dynamically. The library I am using for this purpose (vue-form-generator) comes with built-in validators that are directly referenced within the library itself. Here is an example:

"schema": {
  "fields": [{
    "type": "input",
    "inputType": "email",
    "label": "E-mail",
    "model": "email",
    "placeholder": "Email",
    "validator": "VueFormGenerator.validators.email",
    "required": true
  },{
    "type": "submit"
  }]
}

Below is a snippet of my code:

<template>
  <div id="app" v-if="loaded">
    <vue-form-generator :schema="schema" :model="model" :options="formOptions"></vue-form-generator>
  </div>
</template>

<script>
  /* eslint no-eval: 0 */

  import Vue from 'vue'
  import VueFormGenerator from 'vue-form-generator/dist/vfg-core.js'
  import 'vue-form-generator/dist/vfg-core.css'

  Vue.use(VueFormGenerator)

  export default {
    name: 'app',

    data: function () {
      return {
        loaded: false,
        model: null,
        schema: null,
        formOptions: null
      }
    },

    created: function () {
      return fetch('http://localhost:3000/forms')
        .then((response) => response.json())
        .then((json) => {
          // evaluating the validator's name
          json.schema.fields.map((field) => {
            if (field.validator) {
              field.validator = eval(field.validator)
            }
            return field
          })

          // assigning the schema and model
          this.model = json.model
          this.schema = json.schema
          this.formOptions = json.formOptions

          // indicating that the schema has been loaded
          this.loaded = true
        })
        .catch((ex) => {
          console.log('parsing failed', ex)
        })
    }
  }
</script>

I attempted to use eval() to dynamically evaluate the validator's name and convert it into an actual function. However, this resulted in the following error message:

parsing failed ReferenceError: VueFormGenerator is not defined
    at eval (eval at <anonymous> (eval at <anonymous> (http://localhost:8080/app.js:797:1)), <anonymous>:1:1)
    at eval (eval at <anonymous> (http://localhost:8080/app.js:797:1), <anonymous>:35:29)
    at Array.map (native)
    at eval (eval at <anonymous> (http://localhost:8080/app.js:797:1), <anonymous>:33:26)
    at <anonymous>

Would it be advisable to create a local translation to map validator names to their corresponding functions, or is there another approach that can be taken?

Thank you!

Answer №1

One option to consider is utilizing the reduce method:

      json.schema.fields.map((field) => {
        if (field.validator) {
          // Extract all keys after VueFormGenerator
          const keys = field.validator.split('.').slice(1)
          // Utilize reduce function to retrieve the deepest property
          field.validator = keys.reduce((obj, key) => obj[key], VueFormGenerator)
        }
        return field
      })

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

Unable to begin the previous project on my Mac, but it functions properly on Windows

After running npm i, I encountered the following error message which I am unsure how to resolve. I tried reinstalling Node.js, Python, and Pyenv, but the issue persists. Interestingly, the same version of Node.js on Windows runs the project without any p ...

After submitting the form, Axios sends multiple requests simultaneously

Recently, I embarked on a small project that involves using Laravel and Nuxt Js. The main objective of the project is to create a form for adding users to the database. Everything seems to be progressing smoothly, but there's a minor issue that I&apos ...

AngularJS requires that JSON object property values be converted to strings in order to be displayed as actual templates

Each tab click accesses a json array containing unique templates such as ui-grid or c3 chart directive (c3.js). When a specific tab is clicked, the template in string format must be rendered into actual templates like ui-grid, c3-chart, etc. var sampleJs ...

Is it possible to verify the data within a VueJS model? It seems that none of the Vue validators are effective

Hello there, It's common knowledge that using Vue-validator with most UI components can be challenging when it comes to validation. I've been utilizing Vue Material Components by @mjanys, which is a fantastic library. The author has included met ...

Tips for incorporating Javascript in an innerHTML inline css situation

I'm just starting to learn about html5 and php. I'm curious about how to incorporate javascript into my existing code. Currently, I have data from a database displayed in an HTML table. My goal is to align the output of the last cell more toward ...

Can you iterate through each element that matches those in a different array?

As a beginner in Javascript, I may stumble upon some obvious errors, so please bear with me. My goal is to iterate through two arrays and perform a loop for each element that exists in both arrays. Currently, this is my code: if(obtainedCards.some( sp =& ...

Is there a way to retrieve the parent window's domain in a child window (opened with window.open) when both windows are located on different

Can anyone offer assistance with cross-domain communication between windows? Looking to use window.open(); function. ...

npm ERROR! The module './access-error.js' could not be located

I keep encountering an issue with NPM where I always get the error message npm ERR! Cannot find module './access-error.js'. Can anyone provide assistance? The problem initially arose when attempting to install vue-chartjs. Following the document ...

Unresolved dependencies causing a rollup error

When I try to use import file from 'file.json' in a Vue component and run npm run build to bundle it with Rollup, I encounter an issue. An error is thrown during the process, preventing the file from being bundled as expected. This is the conte ...

Better ways to conceal notifications as soon as a new one appears with Toastr

Whenever a new notification pops up in my application, I desire for the previous one to automatically disappear. It is crucial for only one notification to be displayed at any given time. Is there a way to accomplish this using toastr? ...

The 'Access-Control-Allow-Origin' header is missing

I am encountering the following issue: XMLHttpRequest is unable to load http://localhost:8000/scripts/advaced_donwload/advancedUpload/vueupload/store.php. The requested resource lacks the 'Access-Control-Allow-Origin' header. As a result, ...

Guide to displaying aggregated table field values in an input field when checking the checkbox

How can I retrieve the value of the second span and display it in an input field when a checkbox is checked? For example, if there are values like 500 in the first row and 200 in the second row, when the checkbox in the first row is ticked, the value of 50 ...

Guide to importing VRML Files with three.js

I am encountering an issue with importing a VRML file in three.js. Below is the content of the VRML file: #VRML V2.0 utf8 #Created by CINEMA 4D DEF B1 Transform { translation 600 0 0.333333 children [ DEF _60_ Transform { translation -600 0 0 ch ...

Error message in Leaflet JS: Unable to access property 'addLayer' because it is undefined when trying to display drawnItems on the Map

My attempt to showcase a Leaflet Map with polygon-shaped surfaces encountered an issue. Sometimes, I face the error "cannot read property 'addLayer' of undefined," but when the page is refreshed, the map renders correctly. I am unsure where I wen ...

Utilizing JavaScript to conceal div elements within a ul container

How can I hide specific div tags inside a ul tag using JavaScript? All div tags are currently getting hidden when I use the id of the ul tag. However, I need only the first div tag to be shown and the rest to be hidden. Here is the HTML code: <ul clas ...

jQuery struggles to process large response

I am currently developing an application that sends requests to a URL and parses the table found in the HTML response using jQuery. While this method works well for smaller amounts of HTML code, it runs into issues with larger datasets. The problem arises ...

Is there a way to continue a failed fetch request?

I am curious about the possibility of resuming an incomplete fetch request if it fails due to a non-code-related issue, like a lost network connection. In one of my current projects, we send a large download via AJAX to the client after they log in. This ...

Exploring Nodejs and delving into fundamental queries

As I delved into the world of Nodejs, I quickly realized that my knowledge was limited to just being a user. Transitioning to creating my own server posed challenges that were not easily resolved by online tutorials. This led me here seeking guidance to tr ...

Retrieve both positive and negative reviews using the Steam API

I'm trying to calculate the percentage of positive reviews, but I haven't been able to find the necessary data. I've been using this endpoint to retrieve game information: "", but it only provides the total number of reviews. I am aware of a ...

Getting the x-axis points on Google charts to start at the far left point

I have integrated the Google API for charts into my application and am using multiple charts on the same page. However, I am facing an issue with setting padding for the charts. When I include more data points, the chart area occupies more space in the div ...