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
322 views
in Technique[技术] by (71.8m points)

javascript - 使用数字键将JavaScript对象转换为数组(Converting JavaScript object with numeric keys into array)

I have an object like this coming back as a JSON response from the server:(我有一个像这样的对象作为来自服务器的JSON响应返回:)

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

I want to convert it into a JavaScript array like this:(我想将它转换为像这样的JavaScript数组:)

["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?(那么有没有其他方法来做到这一点?)   ask by Nikhil Agrawal translate from so

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

1 Reply

0 votes
by (71.8m points)

It's actually very straight forward with jQuery's $.map(它实际上非常直接使用jQuery的$.map)

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

FIDDLE(小提琴)

and almost as easy without jQuery as well, converting the keys to an array and then mapping back the values with Array.map(并且在没有jQuery的情况下几乎同样容易,将键转换为数组,然后使用Array.map将值映射回来)

var arr = Object.keys(obj).map(function(k) { return obj[k] });

FIDDLE(小提琴)

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.(这假设它已经被解析为javascript对象,并且实际上不是JSON,这是一种字符串格式,在这种情况下,也需要运行JSON.parse 。)

In ES2015 there's Object.values to the rescue, which makes this a breeze(在ES2015中有拯救的Object.values ,这使得这一切变得轻而易举)

var arr = Object.values(obj);

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

...