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

Error in React Typescript: No suitable index signature with parameter type 'string' was located on the specified type

I have encountered an issue while trying to dynamically add and remove form fields, particularly in assigning a value for an object property. The error message I received is as follows: Element implicitly has an 'any' type because expression o ...

displaying 'undefined' upon completion of iterating through a JSON file using $.each

For my project, I am attempting to extract only the date data from a JSON object. I have successfully looped through the object and displayed it, but the issue arises at the end of the loop where it shows undefined. I am not sure what mistake I am making. ...

Expanding a table by including a new column using Node.js and Knex

Currently building a service for my router using Node.js and Knex, but I'm struggling to add a column to an existing table. Any assistance would be greatly appreciated. Even though I am working with PostgreSQL, I believe the solution will be similar r ...

I am having trouble with a property that I believe should be recognized but is not

Here is the vocabulary I am working with: type MyHeaders = { Authorization: string; Accept: "application/json"; }; type MyGetOptions = { url: string; json: true; }; type MyOptionsWithHeaders = { headers: MyHeaders; }; type MyPostOptions ...

Implementing Cross-Origin Resource Sharing (CORS) in play-framework version 2.5.x: A Step-by-Step Guide

My current challenge involves retrieving JSON data by sending a request to a Restful URL from localhost within an AngularJS-1 application. The error that I encounter is as follows: http://localhost:9000/mlm/user/all Failed to load resource: the server r ...

Typescript excels at gracefully handling cases where an element is not found

While working with Typescript-Protractor Jasmine, I encountered an issue where the test case (the 'it' block) is not failing when an element is not found. Instead, it shows an UnhandledPromiseRejectionWarning but still marks the script as passed. ...

All Pages Except Index in Vue Website Report "404 Error: /path Not Found"

Using Vue with Node.js to host my website on an AWS EC2 instance. I don't have a main index node.js file, just the vue-router file. Utilizing AWS CloudFront to secure my certificate and traffic. The issue arises when accessing the site through the ser ...

Ways to Increase jQuery Element ID

I have several instances of jPlayer (a jQuery audio player) set up: jPlayer1, jPlayer2, jPlayer3, jPlayer4. Each one is initialized and preloaded with audio files. The following function will loop through an existing array and attach a method to play the ...

Controlling a generic interface's acceptance of certain data types in typescript: a guide

Is there a way to restrict a generic interface from accepting specific data types in TypeScript? I understand that I can define acceptable data types for a generic interface in TypeScript. interface exampleInterface<T = void | any>; But what if I w ...

What is the best way to change a javascript string into HTML so that it can be shown in a form?

I am struggling to find a solution to this issue. I am fairly new to jQuery and JavaScript, so please forgive me if my question seems basic. I am trying to call a cfc (ColdFusion) using jQuery and retrieve HTML data. However, when I receive the data, it ...

The user is defined, but the user's user ID is not specified

It seems that the user is defined, but user.user_id is not. My framework of choice is express.js and passport.js. router.post('/requestSale', function(req,res){ console.log('session user: ' + req.session.passport.user); //logs ...

Ajax request in Rails not receiving a response from the controller

After troubleshooting a simple GET request to the controller action, I confirmed that the request is being made successfully and there are no issues with the controller executing the action. However, I am not receiving any response data. $.ajax({ url: ...

Enhancing NG Style in Angular 6 using a custom function

Today, my curiosity lies in the NG Style with Angular 6. Specifically, I am seeking guidance on how to dynamically update [ngStyle] when utilizing a function to determine the value. To better illustrate my query, let me present a simplified scenario: I ha ...

Is searching for duplicate entries in an array using a specific key?

Below is an array structure: [ { "Date": "2020-07", "data": [ { "id": "35ebd073-600c-4be4-a750-41c4be5ed24a", "Date": "2020-07-03T00:00:00.000Z", ...

Is incorporating RequireJS into an AngularJS project a valuable decision?

Is it true that AngularJS has its own module loading mechanism built-in and using RequireJS is unnecessary or even inefficient? I am working on an Angular project where the index.html file is becoming quite large. Would incorporating RequireJS help reduc ...

Cross-Origin Resource Sharing (CORS) verification for WebSocket connections

I am currently utilizing expressjs and have implemented cors validation to allow all origins. const options = { origin: ['*'], credentials: true, exposedHeaders: false, preflightContinue: false, optionsSuccessStatus: 204, methods: [&a ...

Retrieving JSON data in Angular 2

There are limited options available on SO, but it seems they are no longer viable. Angular 2 is constantly evolving... I am attempting to retrieve data from a JSON file in my project. The JSON file is named items.json. I am pondering if I can achieve th ...

Combining various functions into a single button

I am currently working on creating a full-screen menu that functions like a modal. Everything seems to be working fine, except for the fadeOut animation. Can someone please help me understand what is causing issues with my scripts/codes? I want the content ...

In JavaScript/jQuery, there is a technique for retrieving the values of dynamically generated td attributes and the id tags of elements inside them within tr

I am currently working on creating a calendar of events using PHP, jQuery, and ajax. The calendar is embedded within an HTML table, where the rows and fields are dynamically generated based on the number of days in a specific month. In order to successfull ...

The automated Login Pop Up button appears on its own and does not immediately redirect to the login form

Hey guys, I'm struggling with modifying the jquery and html to ensure that when the login button is clicked, the login form pops up instead of displaying another login button. Another issue I am facing is that the login button seems to pop up automati ...