Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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()?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
669 views
Welcome To Ask or Share your Answers For Others

1 Answer

.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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...