转换JSON对象到JavaScript数组 [英] Converting JSON Object into Javascript array

查看:147
本文介绍了转换JSON对象到JavaScript数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON对象像这样回来作为服务器响应:

I have a JSON object like this coming back as a server response:

{"0":"1","1":"2","2":"3","3":"4"}

我想它转换成JavaScript数组,如:

I want to convert it into JavaScript array like:

["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的 $。图

It's actually very straight forward with jQuery's $.map

var arr = $.map(obj, function(el) { return el });

FIDDLE

和几乎一样简单没有了jQuery,转换键的数组,然后映射回值与<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\"><$c$c>Array.map

and almost as easy without jQuery, 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] });

FIDDLE

这是假设它已经被解析为一个JavaScript对象,实际上不是JSON,这通常是一个字符串格式,在这种情况下,通过 JSON.parse 运行会是neccessary为好。

That's assuming it's already parsed as a javascript object, and isn't actually JSON, which is generally a string format, in that case a run through JSON.parse would be neccessary as well.

这篇关于转换JSON对象到JavaScript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆