enguerran
enguerran

Reputation: 3291

Getting complex attribute value of object

Given json like this :

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

In javascript, I can retrieve value like this :

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'];
});

Is this a way, given the attribute name in a string format, to retrieve the value of a complex object, for instance json.text[0].author.name?

EDIT I would like to store the needed attributes in another object like :

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

Upvotes: 0

Views: 845

Answers (3)

Oleg V. Volkov
Oleg V. Volkov

Reputation: 22421

You can split your "index" by . and loop over "segments", descending through levels on each iteration.

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'))

Upvotes: 3

enguerran
enguerran

Reputation: 3291

Yent give a good hint in the comments with the eval function. I resolve my needed with this kind of code:

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);
});

Upvotes: -2

Q2Ftb3k
Q2Ftb3k

Reputation: 688

The following should fix the problem.

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

You can also store the object itself as:

var author = val['author'];

And then later on you can index the attributes from that.

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

Upvotes: 2

Related Questions