验证对象中的字符串

时间:2016-08-25 09:53:18

标签: javascript

我有以下对象:

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

我如何动态获取价值:

我希望通过将层次结构作为字符串

传递来获取值
console.log("Username: ", obj["creds.username"]);
console.log("CreditNumber: ", obj["account.credit.number"]);

注意:对象可能有第n个深子对象

请告诉我一个动态的解决方案

2 个答案:

答案 0 :(得分:3)

如果您希望按[]获取值,请使用密钥作为字符串['account'],或者您可以使用原生方式obj.key.childKey

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

console.log("Username: ", myJson['crews']['username']);
console.log("CreditNumber: ", myJson['account']['credit']['number']);

答案 1 :(得分:1)

只需使用点符号访问该值:

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