0

I have a GET request that sends back a JSON object structured like this:

{"ID":5176,
"DateFrom":"8/29/2018",
"DateTo":"8/29/2018",
"Units":[{"Key":"Value","Key2": "Value2"}]
}

I cannot access Units[0] value. I have tried the following:

testFunction(){
this.service.getJSON(params)
.subscribe((data) => { 
  this.model = data;
  this.dateFrom = this.model.DateFrom;
  this.dateTo = this.model.DateTo;
  this.unit = this.model.Units.Key;
  console.log(this.unit); //undefined
  }); 
 }
}
ngOnInit() {
this.testFunction();

}

What am I missing?

3
  • 2
    this.unit = this.model.Units[0].Key; Commented Aug 31, 2018 at 15:44
  • There's no such thing as a "JSON Object". data is an object, no JSON involved in the "problem". Commented Aug 31, 2018 at 15:45
  • this.unit = this.model.Units[0]; and this.unit.key return your value... Commented Aug 31, 2018 at 15:51

2 Answers 2

1

You should use

this.unit = this.model.Units[0].Key;

instead of

this.unit = this.model.Units.Key; 

since Units.Key is undefined

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

5 Comments

I tried that and now receive this error: "Unable to get property 'Key' of undefined or null reference"
are you sure you are receiving the json from your service? try console.log(this.model) to confirm .
I am sure its coming back as my date properties are able to be bound on my view
This is 100% correct...I foolishly thought I was specifying the index on Key and using 'this.model.Units[1].Key' and it returned undefined because well...a 2nd object didn't exist -_-. Thanks!
Your welcome. Please accept the answer so it will help some else as well
0

Since Units is an array of JSONs and the array contains only one element. It should be accessed by Units[0].

Units[0] is now a JSON, Key property is needed now. There are 2 ways to access it

  1. Units[0].Key
  2. Units[0]['Key']

The final code should look like

testFunction(){
this.service.getJSON(params)
.subscribe((data) => { 
  this.model = data;
  this.dateFrom = this.model.DateFrom;
  this.dateTo = this.model.DateTo;
  //first method
  //this.unit = this.model.Units[0].Key;
  // second method
  // this.unit = this.model.Units[0]['Key'];

  console.log(this.unit); //undefined
  }); 
 }
}
ngOnInit() {
this.testFunction();

}

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.