2

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

3
  • JSON.parse(data);? Should already an be an object after res.json(), why are you parsing it? Commented Jun 23, 2020 at 17:59
  • You have a typo? You objValues and then on the next line you have objKeys. Commented Jun 23, 2020 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. Commented Jun 23, 2020 at 18:00

1 Answer 1

6

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.