0

I'm working with some specific library for forms in javascript. In this library if I have:

{
    "id": 1,
    "order": 0,
    "title": "A title",
},

I can do:

const field = 'order';
form.getState().values[field]

And I'll get the title value.

Now let's say that I have this data:

{
    "id": 1,
    "order": 0,
    "title": "A title",
    "Tags": [
        {
            "id": 1,
            "name": "Tag one",
        },
        {
            "id": 2,
            "name": "Tag two",
        }
    ]
},

And also I have access to a string with the name of the field for tags, the index of the array, and the field I want to retrieve. But I have all this in a string:

Tags[0].name

If I do:

const field = 'Tags[0].name';
form.getState().values[field]

It will return undefined, because will try to find the key Tags[0].name in the object. So: how can I do to retrieve the name property from a specific index in the Tags array, having Tags[0].name as a string?

0

1 Answer 1

0

A bit nasty but quick and working way to do it is to use eval:

const field = 'Tags[0].name';
let stateValues = form.getState().values;
let tagName = eval(`stateValues.${ field }`)

Other approach might be to split and parse the field path using regexp and then traverse the object property by property.

Sign up to request clarification or add additional context in comments.

5 Comments

Didn't know about eval. Clean and clever… Thanks!
By the way, why nasty?
@nikita cause eval is 1) slow 2) kills performance
But in that case I'd say it's not that easy to determine what is faster: a short eval or manual string parsing using not so straightforward regexp.
After reading about it looks like an overused feature of Javascript time ago. Anyway, probably is justified here.