javascriptstringpropertiesobject-property

JS: property-value of an object contains in turn multiple values in a string. How to Access them?


I'm having a Problem accessing a property value of an object in JS. The property value is called "_value" and contains a String. That string again is devided in some other values. Have a look at the image in this post to get an idea what I'm talking about ;)

JS Property-Value contains in turn multiple values in a string.

My question is how can I access these specific values. For example in a way like:

x = sampleObject[0]._value.person
print(x) = 1
 y = sampleObject[0]._value.V_number
print(y) = sg
z = sampleObject[0]._value.tense
print(z) = past
...

...as result getting the values of the first entry in the image.

I think I could try to access the "_value" first. And than make multiple operations on the returning string. But this seems to me very complicated especially cause the returning strings "_values" differ in the sub-properties they contain.

The perfect solution would be to have in the and an object with all values by their own like

Object[x] = {_begin: "4"
             _end: "9"
             _sofa: "6"
             _case: "nom"
             _number: "sg"
             _gender: "masc"
             ...
             _xmi:id: "2625"
             ...}

Unfortunalety I am not generating the objects by myself. The object is a result of reading in a xml-file. So for me there is actually no possibility to write all values of that string in their own entry.

I would be pleased to hear some possible solutions or ideas from you.

Thanks!


Solution

  • A string is ... just a string, so you cannot access parts of it as if it is a structured object.

    That _value property seems to follow the syntax of "key=value|key=value|key=value", so I would suggest to parse your array of objects first with this code:

    sampleObject.forEach( o => 
        o._value = Object.assign(...o._value.split('|')
                    .map( pair => pair.split('=') )
                    .map( ([k, v]) => ({ [k]: v }) ))    
    );
    

    and then your code will work. The above piece of code will split the strings into pieces and create objects based on the key/value pairs it finds, and assign that back to the _value properties.

    var sampleObject = [
        { _value: "V_number=sg|person=1|tense=past|mood=ind" }
    ];
    
    sampleObject.forEach( o => 
        o._value = Object.assign(...o._value.split('|')
                    .map( pair => pair.split('=') )
                    .map( ([k, v]) => ({ [k]: v }) ))    
    );
    
    console.log(sampleObject[0]._value.person);
    console.log(sampleObject[0]._value.V_number);
    console.log(sampleObject[0]._value.tense);