使用数字键将JavaScript对象转换为数组 [英] Converting JavaScript object with numeric keys into array
问题描述
我有一个这样的对象作为服务器的JSON响应返回:
I have an object like this coming back as a JSON response from the server:
{"0":"1","1":"2","2":"3","3":"4"}
我想将它转换为这样的JavaScript数组:
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?
推荐答案
它实际上非常直接用jQuery的 $。map
It's actually very straight forward with jQuery's $.map
var arr = $.map(obj, function(el) { return el });
并且在没有jQuery的情况下也几乎一样容易,将键转换为数组,然后将值映射回来 数组。地图
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] });
假设它已经被解析为javascript对象,实际上并不是JSON,这是一个字符串格式,在这种情况下,也需要运行 JSON.parse
。
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.
在ES2015中有< a href =https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values =noreferrer> Object.values
救援,这使得这一切变得轻而易举
In ES2015 there's Object.values
to the rescue, which makes this a breeze
var arr = Object.values(obj);
这篇关于使用数字键将JavaScript对象转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!