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?

1 Answers1

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.

Szab
  • 1,263
  • 8
  • 18