When evaluating code with eval, properties of undefined cannot be set, but the process works seamlessly without

Currently, I am attempting to utilize the eval() function to dynamically update a variable that must be accessed by path in the format myArray[0][0[1][0].... Strangely enough, when I try this approach, I encounter the following error:

Uncaught TypeError: Cannot set properties of undefined (setting '$folded')

Interestingly, if I avoid using eval and opt for something like

productCategoriesTree[1].$folded = false
- it works without any issues.

My environment involves Vue 3, so there is a possibility that this error might be related to Vue in some way.

The culprit seems to be the addNewProductCategory() function:

// useProductCategoriesTree.ts
import { v4 as uuidv4 } from 'uuid'
import TreeItem from '@/types/TreeItem'
import { try as tryCatch } from 'radash'
import { getCurrentInstance } from 'vue'
import { ProductCategory, ProductCategoryTreeInput } from '@/types/graphql/graphql'
import productCategoryApi, { FRAGMENT_PRODUCT_CATEGORY_TREE } from '@/api/productCategoryApi'

export function useProductCategoriesTree() {
    let productCategoriesTree = $ref<TreeItem<ProductCategory>[]>([])

    const { emit } = getCurrentInstance() as any

    const getProductCategoriesTree = async () => {
        const [error, productCategories] = await tryCatch(productCategoryApi.getProductCategoryList)(FRAGMENT_PRODUCT_CATEGORY_TREE)

        productCategoriesTree = buildProductCategoriesTree(productCategories)
    }

    const buildProductCategoriesTree = (productCategories: ProductCategory[]): TreeItem<ProductCategory>[] => {
        return productCategories.map(productCategory => ({
            data: productCategory,
            children: (productCategory.children && productCategory.children.length)
                ? buildProductCategoriesTree(productCategory.children)
                : undefined
        }))
    }

    const selectProductCategory = (productCategoryUuid: string) => {
        emit('select', productCategoryUuid)
    }

    // treePath could be [0, 1, 0, 0, 1] - it is dynamic
    const addNewProductCategory = (parentCategoryUuid: string, treePath: number[]) => {
        const newProductCategory = {
            uuid: `__NEW-${uuidv4()}`,
            namePlural: 'new',
            parent: { uuid: parentCategoryUuid }
        }

        if (!productCategoriesTree[1].children) {
            productCategoriesTree[1].children = []
        }

        productCategoriesTree[1].children?.push({
            data: newProductCategory as ProductCategory,
            children: [],
        })

        console.log(`productCategoriesTree[${treePath.join('][')}].$folded = false`)
        // productCategoriesTree[1].$folded = false

        // this works
        productCategoriesTree[1].$folded = false

        // this does not work
        eval(`productCategoriesTree[${treePath.join('][')}].$folded = false`)
    }

    getProductCategoriesTree()
    
    return $$({
        productCategoriesTree,
        selectProductCategory,
        addNewProductCategory,
    })
}

Answer №1

If I were to avoid using eval, I would explore alternative methods. One example could be:

let updatedItem = productCategoriesTree;

treePath.forEach(element => {
  updatedItem = updatedItem[element];
});

updatedItem.$folded = false;

This solution is reminiscent of the problem discussed in this post: JavaScript: Extracting a nested value from an object using a string path

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

What is the correct way to define the onClick event in a React component?

I have been encountering an issue while trying to implement an onClick event in React using tsx. The flexbox and button are being correctly displayed, but I am facing a problem with the onClick event in vscode. I have tried several ideas from the stack com ...

Real-time changes may not be instantly reflected in the model update

I need to add two numbers together and display the sum in a third input field: HTML <div ng-app="myApp"> <div ng-controller="MainCtrl as mainCtrl"> Main {{mainCtrl.foo}} <br/> <input type="text" ng-model="mainCtrl.foo"/> ...

Tips on retrieving and sending an XML string in PHP to JavaScript using MySQL

Here is the code snippet I have: <input type='button' value='clickme' onclick='download(\"\" . $rowtable['Protocolo'] . \".xml\", \"\" . $rowtable['XML&a ...

Is there any benefit to making the SVG elements width and height 100%?

The Angular Material documentation app features an SVG Viewer that is able to scale the SVG content to fit the container using the following function: inlineSvgContent(template) { this.elementRef.nativeElement.innerHTML = template; if (this.sca ...

What is the most effective way to loop through an object containing DOM selectors as values, and subsequently utilize them to assign new values?

I have a function that takes an object retrieved from a database as its argument. My goal is to display the values of this object in a form by associating each value with a specific DOM selector. Here is the code snippet where I achieve this: function pai ...

Guide to incorporating code coverage in React/NextJs using Typescript (create-next-app) and cypress

I initiated a fresh project using create-next-app with the default settings. npx <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="365544535742531b58534e421b57464676070518021801">[email protected]</a> --- Would you l ...

JavaScript event listener on the "change" event only triggers when changed manually [CodePen]

Check out this jsFiddle I created with all the data and information related to the issue. It should make it easier to understand what's happening: Take a look here: http://jsfiddle.net/lukinhasb/GuZq2/ $("#estado").val(unescape(resultadoCEP["uf"])); ...

Navigating through a URL to grab a specific JSON object: a step-by-step guide

When I receive a json from a URL containing numerous objects, how can I extract only the slugs provided in the json below? I am open to solutions using either PHP or JavaScript. On one hand, I need to understand how to specifically retrieve the desired ob ...

Changing synchronous functions to asynchronous

Attempting to transform synchronous calls into asynchronous ones using when...done. Despite being new at this, after extensive reading on the topic for the past two days, my code should work as intended. However, while it does function, it doesn't exe ...

How can I show a view page in a specific div element using CodeIgniter?

Here is how I'm implementing the dashboard view in my controller. My goal is to have a specific page, like the index page, displayed within a div element rather than opening in a new tab. public function index() { $this->load->view('in ...

The inner HTML functionality in Angular 2 seems to be malfunctioning when dealing with HTML tags

I am facing an issue with an array that includes displayName with HTML tags: this.topicsList = [ {id: "173", name: "Discussion1", displayName: "Discussion1", status: 1}, {id: "174", name: "discussion123", displayName: "discussion123", status: 1}, {id: "19 ...

Angular 14 troubleshooting: Issues with using getRawValue() in IndexOf function

In this scenario, I have a straightforward Person interface defined as: import { FormArray, FormControl, FormGroup } from '@angular/forms'; import { Address } from './address'; export class Person { id: FormControl<number>; n ...

Leveraging react-markdown alongside Material-UI's table component

Currently, I am attempting to parse a markdown table using the react-markdown library and then displaying the resulting tags with the help of the Material-UI table component. Below is the code snippet for my renderer: import withStyles from '@material ...

Interacting with YouTube Data API without requiring user input

I'm currently developing a music website that enables users to create YouTube playlists. Initially, I experimented with JavaScript: https://developers.google.com/youtube/v3/code_samples/javascript The procedure involves an initial authorization ste ...

How can you alter the background color of a Material UI select component when it is selected?

I am attempting to modify the background color of a select element from material ui when it is selected. To help illustrate, I have provided an image that displays how it looks when not selected and selected: Select Currently, there is a large gray backgr ...

Strategies to manage or prevent a timezone offset while deploying a Next.js application on Vercel

Is there a way to ensure that a React/Next.js App always displays the local time in CEST, regardless of the user's location? For example, if I receive GMT time from the backend and want to offset it to display the CEST timezone, how can I achieve this ...

How can I access the parent elements within a recursive directive?

I'm currently implementing a recursive directive called https://github.com/dotJEM/angular-tree to iterate through a model structure like the one below: $scope.model = [ { label: 'parent1', children: [{ ...

Transforming a JSON structure into a tree model for use with the angular-tree-control component

I need help converting a complex JSON schema into a format compatible with Angular Tree Control. The issue is that the schema does not follow the required treemodel structure for Angular Tree Control, particularly because the children in the schema are not ...

Guide on implementing a Pug for loop using AJAX

For my school project, I am developing a web application similar to Tinder using Node.js, Express, and Pug. The main goal of the project is to provide potential matches to users based on either their proximity or common interests with the current user. Whe ...

Guide to deploying a React application using Material-UI and react-router

I've successfully built an application using React, Material-UI, and react-router. Below is the content of my complete package.json: { "name": "trader-ui", "version": "0.1.0", "private": true, "dependencies": { "@material-ui/core": "^3.2. ...