-2
var json ={
    "my_location": {
        "city": "city",
        "title": "my title",
        "complete_address": "my complete address",
        "geo": {
            "lat": 1.11111111,
            "lng": 1.22222222
        }
    }
}

I want to get by a string key name like this

var key_name="my_location.geo.lat"

please help me how i can get the value by usig this key_name in javascript

Hakeem
  • 13
  • 3
  • Provide a way you tried. – hoangdv Apr 02 '21 at 14:20
  • json+key_name and json.{(key_name)} json[key_name] but I am not successfull – Hakeem Apr 02 '21 at 14:21
  • You can get `lat` data by this syntax: `json['my_location']['geo']['lat]` – hoangdv Apr 02 '21 at 14:23
  • This is usually called "object graph navigation", and I am 100% certain there are multiple duplicate questions but I can't find them. The language (JavaScript) does not provide a way to do this, but it's not difficult to implement if you don't need to do anything fancy. – Pointy Apr 02 '21 at 14:24
  • no I need by parsing that string because we will be using this for mapping – Hakeem Apr 02 '21 at 14:25

1 Answers1

0
const getPropValue = (object, path = '') =>
path.split('.')
    .reduce((o, x) => o == undefined ? o : o[x]
    , object)

test with:

getPropValue(json, "my_location.geo.lat")
Victor Luchian
  • 112
  • 1
  • 10