Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

javascript - 使用jQuery将JS对象转换为数组(Converting a JS object to an array using jQuery)

My application creates a JavaScript object, like the following:

(我的应用程序创建了一个JavaScript对象,如下所示:)

myObj= {1:[Array-Data], 2:[Array-Data]}

But I need this object as an array.

(但是我需要将此对象作为数组。)

array[1]:[Array-Data]
array[2]:[Array-Data]

So I tried to convert this object to an array by iterating with $.each through the object and adding the element to an array:

(所以我尝试通过$.each遍历对象并将元素添加到数组中来将该对象转换为数组:)

x=[]
$.each(myObj, function(i,n) {
    x.push(n);});

Is there an better way to convert an object to an array or maybe a function?

(有没有更好的方法将对象转换为数组或函数?)

  ask by The Bndr translate from so

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

1 Answer

0 votes
by (71.8m points)

If you are looking for a functional approach:

(如果您正在寻找一种实用的方法:)

var obj = {1: 11, 2: 22};
var arr = Object.keys(obj).map(function (key) { return obj[key]; });

Results in:

(结果是:)

[11, 22]

The same with an ES6 arrow function:

(与ES6箭头功能相同:)

Object.keys(obj).map(key => obj[key])

With ES7 you will be able to use Object.values instead ( more information ):

(使用ES7,您将可以改为使用Object.values更多信息 ):)

var arr = Object.values(obj);

Or if you are already using Underscore/Lo-Dash:

(或者,如果您已经在使用Underscore / Lo-Dash:)

var arr = _.values(obj)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...