JavaScript,将对象转换为数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4607991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:14:59  来源:igfitidea点击:

JavaScript, transform object into array

javascriptjquery

提问by ?ime Vidas

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?

我会接受这样的功能作为答案。但是,如果有一个 API 函数(ECMAScript、jQuery、特定于浏览器的,...)可以做到这一点,我会更高兴。有这样的事情吗?

采纳答案by Suresh Kumar

Use Object.valuesit will return array.

使用Object.values它将返回数组。

Object.values(obj) // [24, 23, 33, 12, 31]

回答by CMS

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

显而易见的方法是做一个 for-in 循环,正如@quixoto 所建议的那样,但只是为了记录,而且由于您正在寻找一种内置方式,您可以将新的 ECMAScript 5 方法Object.keysArray.prototype.map配对, 在最新的浏览器上可用:

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

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

更新:ES2017 引入了该Object.values方法,它完全符合您的要求。

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

此外,ES2017 添加了另一个常用方法,Object.entries. 此方法返回一个键值对数组。

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

回答by Malte K?hrer

With jQuery you could use the each function:

使用 jQuery,您可以使用 each 函数:

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

myArray=new Array();
$.each(obj, function(key, value) { 
  myArray.push(value);
});

回答by Ben Zotto

There's no built-in way to do this anywhere. The following does what you suggest, and may be "shortened" into more clever functional-programming versions depending on your library, but they'll all have the same efficiency.

没有内置的方法可以在任何地方执行此操作。以下按照您的建议进行操作,并且可能会根据您的库被“缩短”为更聪明的函数式编程版本,但它们都具有相同的效率。

function valuesToArray(obj) {
    var result = [];
    for (var key in obj) {
       if (obj.hasOwnProperty(key)) {
           result.push(obj[key]);
       }
    }
    return result;
}

回答by user113716

Posting this strictly for fun. Save your downvotes. I'm not recommending it actually be used. ;o)

发布此严格为了好玩。保存您的反对票。我不建议实际使用它。;o)

Example:http://jsfiddle.net/WGpXX/

示例:http : //jsfiddle.net/WGpXX/

var arr = eval( '[' +
    JSON.stringify(obj)
    .slice(1,-1)
    .replace(/"[^"]+":/g,'')
    + ']');

Technicallyworks in this simple case.

在这种简单的情况下,技术上可行。

回答by pjbrito

Using the Underscore lib try:

使用下划线库尝试:

function valuesToArray(o) {
    return _.pairs(o);
}

var obj = {
    "Mike": 24,
    "Peter": 23
    //...
    },
    result = valuesToArray(obj);

Then the result is [ ["Mike", 24], ["Peter", 23] ];

那么结果是 [ ["Mike", 24], ["Peter", 23] ];

More detail on the pairs method here: http://underscorejs.org/#pairs

关于pairs方法的更多细节:http: //underscorejs.org/#pairs

回答by Tengiz

Using bob.jsthis can be done pretty simply:

使用bob.js这可以非常简单地完成:

function valuesToArray(obj) {
    return bob.collections.extensions.toArray.call(obj);
}

回答by Chandu

Try this:

尝试这个:

var obj = {     "Mike": 24,     "Peter": 23,     "Simon": 33,     "Tom": 12,     "Frank": 31 } ;
    var arr = []
    for(var a in obj)
    {
        var val = obj[a];
        arr.push(val);
    }
alert(arr.length)

回答by jvenema

Some libraries have something to do this (such as prototype's "values" function), but they're really just wrappers around a function that loops over and returns the values of the object.

一些库可以做到这一点(例如原型的“值”函数),但它们实际上只是一个函数的包装器,该函数循环并返回对象的值。

http://www.prototypejs.org/api/object/values

http://www.prototypejs.org/api/object/values