获取对象的复杂属性值

时间:2012-07-23 14:48:04

标签: javascript jquery

鉴于json是这样的:

{ "rss": {
   "page": 1,
   "results": [{
      "type": "text",
      "$": 10
   }],
   "text": [{
      "content": "Lorem ipsum dolor sit amet.",
      "author": {
         "name": "Cesar",
         "email": "cesar@evoria.com"
      },
   },
   {
      "content": "Tema Tis rolod muspi merol.",
      "author": {
         "name": "Cleopatre",
         "email": "cleopatre@pyramid.com"
      },
   }]
}

在javascript中,我可以检索这样的值:

var json = JSON.parse(datajson);
$.each(json.text, function(key, val) {
    // this one is ok
    var content = val['content'];
    // this one does not work
    var authorname = val['author.name'];
});

这是一种方法,给定字符串格式的属性名称,以检索复杂对象的值,例如json.text[0].author.name

修改 我想将所需的属性存储在另一个对象中,如:

[
    { dt: "Text content", dd: "content" },
    { dt: "Author name", dd: "author.name"}
]

3 个答案:

答案 0 :(得分:3)

您可以将“索引”拆分为.并循环“细分”,在每次迭代时降低级别。

var obj = {
   author : {
      name : "AuthorName"
   }
}

function get_deep_index(obj, index) {   
   var segments = index.split('.')
   var segments_len = segments.length
   var currently_at = obj
   for(var idx = 0; idx < segments_len; idx++) {
      currently_at = currently_at[segments[idx]]
   }
   return currently_at
}

console.log(get_deep_index(obj, 'author.name'))

答案 1 :(得分:2)

以下内容应解决问题。

var authorname = val['author']['name'];

您还可以将对象本身存储为:

var author = val['author'];

然后您可以从中索引属性。

console.log(author.name, author.email)

答案 2 :(得分:-2)

在评论中使用eval函数提供了很好的提示。我用这种代码解决了我的需要:

var json = JSON.parse(myjsonasastring);

var descriptiontobeadded = [
    { dt: "Text content", dd: "content" },
    { dt: "Author name", dd: "author.name" }
];

$.each(descriptiontobeadded, function(key, val) {
    var dt = '<dt>' + val.dt + '</dt>';
    description.append(dt);
    var dl = '<dd>' + eval('json.' + val.dd) + '</dd>';
    description.append(dl);
});