1

after looking through a lot of similar questions on SO, I still can't iterate my json structure. How can I reach the value (key) of my inner array?

var data = {"User1":{"Service1":2,"Service2":1},"User2":{"Service3":1}}
            
for(var user in data) {
    document.write(user + ': ')
             
    for(var service in data[user]){
        document.write(service + ': ' + user[service])
    }
    document.write("<br />")
}

This prints:

User1: Service1: undefined Service2: undefined

User2: Service3: undefined

And I'd like it to print

User1: Service1: 2 Service2: 1

User2: Service3: 1

Is javascript enough or do I need jQuery? Thanks in advance!

1
  • There is no "inner array", there are nested objects though. Commented Jun 1, 2011 at 9:00

2 Answers 2

8
var data = {
  User1: {
    Service1: 2,
    Service2: 1
  },
  User2: {
    Service3: 1
  }
};
for (var user in data) {
  console.log("User: " + user);
  for (var service in data[user]) {
    console.log("\tService: " + service + "; value: " + data[user][service]);
  }
}

Replace console.log with document.write or whatever.

Sign up to request clarification or add additional context in comments.

1 Comment

Could have sworn I tried that but I must've written data[user[service]]. Silly me. Thank you!
3

document.write(service + ': ' + data[user][service])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.