Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

jquery - JavaScript, transform object into array

I've got an object:

var obj = {
    "Mike": 24,
    "Peter": 23,
    "Simon": 33,
    "Tom": 12,
    "Frank": 31
};

I want to create an array that holds the values of the object. The keys (key names) can be disregarded:

[24, 23, 33, 12, 31]

The order of the values is NOT important!

One solution (obviously) would be do have a function that takes the values and puts them into an array:

var arr = valuesToArray(obj); 

I will accept such a function as the answer. However, I would be more pleased if there would be an API function (ECMAScript, jQuery, browser-specific, ...) that could do this. Is there such a thing?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The obvious way would be to do a for-in loop, as @quixoto suggests, but just for the record, and since you are looking for a built-in way, you could pair the new ECMAScript 5 methods Object.keys and Array.prototype.map, available on latest browsers:

function valuesToArray(obj) {
  return Object.keys(obj).map(function (key) { return obj[key]; });
}

UPDATE: ES2017 introduced the Object.values method, which does exactly what you want.

Additionally, ES2017 adds another often useful method, Object.entries. This method returns an array of key-value pairs.

const obj = {
    "Mike": 24,
    "Peter": 23,
    "Simon": 33,
    "Tom": 12,
    "Frank": 31
};

const values = Object.values(obj);
const entries = Object.entries(obj);
console.log('values:', values);
console.log('entries:', entries);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...