Search code examples
javascriptjsonangularnestedconcatenation

How to access a value in nested JSON with all fields concatenated in Angular?


Let's say I have this JSON in this variable person:

{
    "firstName": "First Name"
    "lastName": "Last Name"
    "address": {
        "city": "New-York",
        "street": "Some Street"
    }
}

Now, if I want the value of street, all I have to do is person[address][street]

I was wondering if there is a simple way to do so, let's say I have all the fields concatenated like:

const index = 'address:street'

I'm looking for a simple way to achieve the value like person[index]

Is there a way to do so? thanks!


Solution

  • Found the answer, I installed lodash and then:

    import _ from 'lodash';
    
    const person = {
        "firstName": "First Name"
        "lastName": "Last Name"
        "address": {
        "city": "New-York",
        "street": "Some Street"
        }
    }
    
    const index = 'address.street'; // changed it to be split by . instead of :
    
    _.get(person, index);