-2

I have a javascript object of the form

var fruits = {
    "1": {
         "id": 1,
         "description": "Apple",
         "groupID": 0
    },
    "2": {
         "id": 2,
         "description": "Peach",
         "groupID": 0
     }
}

This javascript has been obtained as a JSON response after AJAX call. How do I extract the variable data (description) here? P.S. no jQuery

what I did was

 for(i=0;i<fruits.length;i++){
     j=i+1;
     console.log(fruits[j].description);
 }

it says fruits[j] is undefined.

Sébastien
  • 11,860
  • 11
  • 58
  • 78
user5673235
  • 21
  • 1
  • 9
  • Did you take a look at [Javascript Objects](https://www.w3schools.com/js/js_objects.asp) before asking ? – Zenoo Feb 05 '18 at 20:43
  • 1
    @Zenoo please don't link to that awful site. ;) – Sébastien Feb 05 '18 at 20:43
  • Possible duplicate of [Access / process (nested) objects, arrays or JSON](https://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Tibrogargan Feb 05 '18 at 20:46
  • @Zenoo yes I did. Let me repeat once again that this is an object that I am getting after AJAX call. console.log(fruits); prints well but when I do console.log(fruits[1].description); it returns undefined. – user5673235 Feb 05 '18 at 21:16
  • You have not put the actual code, nor the output that you are seeing in the question. It could be as simple as failing to use `JSON.parse()` on the response from the Ajax call. You need to provide what you actually have, not attempt to paraphrase it – Tibrogargan Feb 05 '18 at 22:23

1 Answers1

0

You can use for ... in loop to loop trough them and get the descriptions, or Object.values and map to get an array of the values;

 var fruits =
  {
    "1": {
          "id": 1,
          "description": "Apple",
          "groupID": 0
         },
    "2": {
          "id": 2,
          "description": "Peach",
          "groupID": 0
         }
  }
  
for(let key in fruits)
{
  console.log(fruits[key].description);
}

console.log(Object.values(fruits).map(v => v.description));
mdatsev
  • 3,054
  • 13
  • 28
  • I am getting this object after an AJAX call. When I do console.log(fruits); , it print well, but if I try to access any of its members as you said, it says undefined. What do I do? – user5673235 Feb 05 '18 at 21:01
  • @user5673235 If `Object.values(fruits)` does not return anything meaningful, then it's not an object... – Andrew Feb 05 '18 at 21:08
  • console.log(Object.values(fruits)) ? says "Unresolved function or method values()" – user5673235 Feb 05 '18 at 21:19