Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught TypeError: Object.values is not a function JavaScript

I have a simple object like the one below:

var countries = {     "Argentina":1,     "Canada":2,     "Egypt":1, }; 

I need to create two arrays. The first array is an array of all the keys from the object. I created this array by:

var labels = Object.keys(countries); 

This works well. I obtain an array of countries. Now when I try to create an array from the values...

var labels = Object.values(countries); 

I get this error: Uncaught TypeError: Object.values is not a function JavaScript

I don't know what I am doing wrong. I console.log countries before and after I declare labels and the object remains the same. How do I properly use Object.values()?

like image 307
Alex Fallenstedt Avatar asked Aug 03 '16 15:08

Alex Fallenstedt


People also ask

What is uncaught TypeError in JavaScript?

Educative Answers Team. According to the Mozilla website for developer documents, “the TypeError object represents an error when a value is not of the expected type.” Uncaught means that the error was not caught in the catch part of the try-catch block.

Is not a function JavaScript error?

The JavaScript exception "is not a function" occurs when there was an attempt to call a value from a function, but the value is not actually a function.

How do you change an object to an array?

JavaScript Objects Convert object's values to array You can convert its values to an array by doing: var array = Object. keys(obj) . map(function(key) { return obj[key]; }); console.


1 Answers

.values is unsupported in many browsers - you can use .map to get an array of all the values:

var vals = Object.keys(countries).map(function(key) {     return countries[key]; }); 

See MDN doc: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values or Official doc: https://tc39.github.io/ecma262/#sec-object.values (thanks @evolutionxbox for correction)

like image 127
tymeJV Avatar answered Oct 02 '22 23:10

tymeJV