问题描述
我有一个像这样的对象作为来自服务器的 JSON 响应返回:
{0":1",1":2",2":3",3":4"}
我想把它转换成这样的 JavaScript 数组:
[1"、2"、3"、4"]
有没有最好的方法来做到这一点?无论我在哪里阅读,人们都在使用循环来使用复杂的逻辑.那么有没有其他方法可以做到这一点?
实际上使用 jQuery 的 非常简单$.map
var arr = $.map(obj, function(el) { return el });
并且在没有 jQuery 的情况下也几乎同样简单,将键转换为数组,然后使用 Array.map
var arr = Object.keys(obj).map(function(k) { return obj[k] });
假设它已经被解析为一个 javascript 对象,并且实际上不是 JSON,它是一种字符串格式,在这种情况下,还需要运行 JSON.parse
.>
在 ES2015 中有 Object.值
到救援,这让这变得轻而易举
var arr = Object.values(obj);
I have an object like this coming back as a JSON response from the server:
{
"0": "1",
"1": "2",
"2": "3",
"3": "4"
}
I want to convert it into a JavaScript array like this:
["1","2","3","4"]
Is there a best way to do this? Wherever I am reading, people are using complex logic using loops. So are there alternative methods to doing this?
It's actually very straight forward with jQuery's $.map
var arr = $.map(obj, function(el) { return el });
and almost as easy without jQuery as well, converting the keys to an array and then mapping back the values with Array.map
var arr = Object.keys(obj).map(function(k) { return obj[k] });
That's assuming it's already parsed as a javascript object, and isn't actually JSON, which is a string format, in that case a run through JSON.parse
would be necessary as well.
In ES2015 there's Object.values
to the rescue, which makes this a breeze
var arr = Object.values(obj);
这篇关于将带有数字键的 JavaScript 对象转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!