1

I am using the fetch api to fetch some data from my own back-end api. As I know fetch gives us a response we must convert it into a json to read the body of the response.The resulting data is in form of json.

    fetch(`/user/getFriends?steam64=${dataObj.persondata.steamid}`,{
    method:"GET",
  })
   .then(res=> res.json())
   .then((data)=>{
     const obj = JSON.parse(data);
     const objValues = Object.values(obj);
     console.log(typeof objKeys); //object
   });

As we can see in the code above.I am converting the json back to object by using JSON.parse and storing it into a variable called 'obj'.Then I am using Object.values(); To extract the values from the object and store it in an array.

But if I check the type of 'objValues' it returns object rather than array. Please help me out.Any help regarding this is greatly appriciated.THANK YOU

DeADLY
  • 69
  • 1
  • 6
  • `JSON.parse(data);`? Should already an be an object after `res.json()`, why are you parsing it? – VLAZ Jun 23 '20 at 17:59
  • You have a typo? You `objValues` and then on the next line you have `objKeys`. – Rahul Bhobe Jun 23 '20 at 18:00
  • 1
    "*if I check the type of 'objValues' it returns object rather than array*" because `typeof` can only report `"object"` - arrays *are* objects in JavaScript. – VLAZ Jun 23 '20 at 18:00

1 Answers1

4

typeof always returns "object" for an array.

console.log(typeof []);
console.log(typeof [1,2,3]);

Use Array.isArray to check if an object is an array.

console.log(Array.isArray([])); //true
console.log(Array.isArray([1,2,3])); //true
console.log(Array.isArray({})); //false
Unmitigated
  • 76,500
  • 11
  • 62
  • 80