-1

I have following object:

var obj = {
 "id": 1,
 "name": "john",
 "creds": {
   "username": "abc@yopmail.com"   
 },
 "account": {
  "credit": {
   "number": "123456"
  },
  "name": "accountName"
 }
}

How can i dynamically get value:

I want to get the value by passing the hierarchy as string

console.log("Username: ", obj["creds.username"]);
console.log("CreditNumber: ", obj["account.credit.number"]);

Note: the object might have nth deep child objects

Please advise me a dynamic solution for this

Martin
  • 15,820
  • 4
  • 47
  • 56
maverickosama92
  • 2,685
  • 2
  • 21
  • 35
  • i can't understand your question. You want a sort of for loop that gives you creds.username? – illeb Aug 25 '16 at 09:55
  • @Luxor001: I want to get the value by passing json hierarchy as string. – maverickosama92 Aug 25 '16 at 09:56
  • https://github.com/jayway/JsonPath – mplungjan Aug 25 '16 at 09:56
  • myJson[Creds][username], where Creds = "creds" and username="username" – illeb Aug 25 '16 at 09:57
  • You are not using JSON in your code. This is a JavaScript object. JSON is a string representation of an object, array or value. You can get the values from the object using the following: console.log("Username: ", myJson["creds"]["username"]); console.log("CreditNumber: ", myJson["account"]["credit"]["number"]); Or even simpler: console.log("Username: ", myJson.creds.username); console.log("CreditNumber: ", myJson.account.credit.number); – Martin Aug 25 '16 at 09:59
  • @Quentin: Thanks man, duplicate marked answer solved my query. Thanks all. – maverickosama92 Aug 25 '16 at 10:01
  • `function getProp(obj, prop) { return prop.split('.').reduce(function(o, k) { return o && o[k]; }, obj); }; getProp(obj, "account.credit.number")` – Pranav C Balan Aug 25 '16 at 10:02
  • you can ues a function to do this,like this function:`function demo(str){ var result = myJson; var arr = str.split("\."); for(var i= 0,item;item=arr[i++];){ result = result[item]; } return result; }` and use this function like this:`demo("creds.username")` – Ying Yi Aug 25 '16 at 10:05

2 Answers2

3

If you want to get the value by [] use key as string like, ['account'] or you can use native way obj.key.childKey.

console.log("Username: ", myJson.creds.username);
console.log("CreditNumber: ", myJson.account.credit.number);

or

console.log("Username: ", myJson['crews']['username']);
console.log("CreditNumber: ", myJson['account']['credit']['number']);
Harish Kommuri
  • 2,825
  • 1
  • 22
  • 28
1

Simply by accessing the value with the dot notation:

console.log("Username: ", myJson.creds.username);
console.log("CreditNumber: ", myJson.account.credit.number);
Romain Linsolas
  • 79,475
  • 49
  • 202
  • 273