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.

3
  • Did you notice subjects is an array and you are suppose to pass index to access its properties ? Commented Sep 23, 2018 at 9:03
  • Possible duplicate of Access / process (nested) objects, arrays or JSON Commented Sep 23, 2018 at 9: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.} Commented Sep 23, 2018 at 9:27

3 Answers 3

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);
  ));
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

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

1 Comment

Don't use map when you do not change the array. You should use forEach instead.

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.