0

I am receiving a response in json form like below. How do i loop through to display the user of person1 and person2? I keep getting undefined in my console. What am i not doing right?

data

 {
"person1" :  {
"user": "David"  ,

},
"person2" : {
 "user":  "Crave"  ,
}
}

function

    this.service.fetch(message){

      display1 = message.person1.user;
      display2 = message.person2.user;
}
XamarinDevil
  • 873
  • 5
  • 17
  • 38

3 Answers3

2

There are spaces in your key names. If you remove the spaces before and after user to make it "user" and before and after " person1 " to make it "person1" it should work.

1

Due to the spacing around the attributes, working with this json object will require [] notation. eg. json[" person1 "][" user "]. Removing the spacing will allow us to use . notation. For example:

{
  "person1" :  {
    "user": "David",
  },
  "person2" : {
     "user": "Crave",
  }
} 

Then, to loop through the json object, we can use a for-in to loop through the keys of the object (in this case key = [person1, person2]). If we assume the below users variable equals the json object above:

for(key in users) { 
    console.log(users[key].user) // Will console.log "David", then "Crave"!
}
dpaulus
  • 422
  • 6
  • 16
0

something along these lines should work just fine. You can easily apply the same sort of logic to your issue.

var data =  
{
"person1":{
 "user":"David"},
 "person2":{
 "user":"Crave"
}
};

function show_data(){
 console.log(data.person1.user);
 console.log(data.person2.user);
}

show_data();

This simply makes it easy to assign the object to a variable, and access it in the showdata() function.

Abdul Shaikh
  • 129
  • 9