1

I have the following (snippet) variable:

var txt = {
        'start': {
                 'name':'Call start',
                 'data': {'next':'start/e3fe40'},
                 'id':'start',
                 'type':'standard---start'
        },
        'e3fe40': {
                'name':'Menu',
                'data':  {'next':'end/asd3rg'},
                'id':'e3fe40'
         }
};

I need to parse through the JSON and get info from the 'e3fe40' branch (without knowing how its going to be called.

Here's what I have:

var nxt = txt.start.data.next.substr(6,10); <-- works
console.log(nxt);                           <-- works
console.log(txt.start.data.next);           <-- works
console.log(txt.nxt.name);                  <-- nxt should contain 'e3fe40'

So, how do I go down a branch? txt.nxt.name won't work, txt.{nxt}.name won't work, etc....

Thanks, Dan

5
  • 4
    That isn't JSON. It is a JavaScript object literal. Commented Aug 13, 2012 at 16:33
  • Also the word for what you're doing isn't "parse", if we're picking nits. :-) You need the [ ] operator. Commented Aug 13, 2012 at 16:33
  • You're always going to struggle if you don't know the structure of your incoming data. All you can do is loop over the keys and try to identify what you want that way, but this is far from ideal. Commented Aug 13, 2012 at 16:34
  • txt.nxt should be txt.e3fe40 .. I was trying to substitute e3fe40 with nxt as variable, but dont know how Commented Aug 13, 2012 at 16:34
  • Quentin: the js object literal is initially json received from another app -- i'm posting like this to shorten the code Commented Aug 13, 2012 at 16:36

3 Answers 3

2
var key = txt.start.data.next.substr(6);
console.log(txt[key].name);  
Sign up to request clarification or add additional context in comments.

Comments

0

Assuming nxt = "e3fe40" you get the value by doing.

txt[nxt].name

Different ways of accessing the values,

txt.e3fe40.name txt['e3fe40'].name and one shown above.

txt.nxt.name is wrong. Because nxt is not a key in the Javascript object,

Comments

0

If You debug code by using debugging tool and put this code I think it will solve your problem

alert(txt.e3fe40.name);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.