1

As a ReactJS newbie, I tried to parse RestfulAPI JSON reponse, But, I couldn't retrieve all elements. While trying to access text.subjects.code and text.subjects.description, it returns null. However, I could successfully access text.id and text.name.

JSON response is given below.

[
  {
    "id":95822,
    "name":"Alex",
    "subjects":[
      {
        "code": "101",
        "description": "Course 101"
      }
    ]
  }
]

Kindly advise.

user3362908
  • 433
  • 5
  • 16
  • Did you notice `subjects` is an array and you are suppose to pass index to access its properties ? – Rayon Sep 23 '18 at 09:03
  • Possible duplicate of [Access / process (nested) objects, arrays or JSON](https://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – str Sep 23 '18 at 09:07
  • Now you knew subjects is an array. The best way to avoid error scenario when subjects array is empty and you are trying to get code from it is to use either map() or lodash-get: let code=lodash.get(text.subjects,'[0][code]',undefined) and then check the value if(typeof code != 'undefined') {dosomething.} – ankidaemon Sep 23 '18 at 09:27

3 Answers3

2

You can do iteration in many ways and few ways which I always prefer using .forEach and .map

If you need new array then go with .map. Because map returns a new array

  const dataArray = text.subjects.map(subject => {
      let obj = {};
      obj.code = subject.code;
      obj.description = subject.description;
      return obj;
 });

//dataArray will contain all the objects

There is also a Different way of doing map

   const dataArray = text.subjects.map(subject => (
       let obj = {};
      obj.code = subject.code;
      obj.description = subject.description;
      return obj;
  );

Or if you want to just iterate the data then use .forEach. forEach doesn’t return an array

   let array = [];
   text.subjects.forEach(subject => (
      let obj = {};
      obj.code = subject.code;
      obj.description = subject.description;
      array.push(obj);
  ));
Hemadri Dasari
  • 32,666
  • 37
  • 119
  • 162
1

if You check subjects is an array and you are not getting value from it, try text.subjects[0].code

Japesh
  • 261
  • 3
  • 7
0

Because subjects is an array and you should map subject like the following:

text.subjects.map((subject) => {
    console.log(subject.code, subject.description);
})

or directly get the index that you to want like the following:

text.subjects[0].code

Omid Nikrah
  • 2,444
  • 3
  • 15
  • 30
  • Don't use `map` when you do *not* change the array. You should use `forEach` instead. – str Sep 23 '18 at 09:29