Converting a JS object to an array using jQuery

后端 未结 18 3468
鱼传尺愫
鱼传尺愫 2020-11-22 01:37

My application creates a JavaScript object, like the following:

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

But I need this object as an array.

18条回答
  •  半阙折子戏
    2020-11-22 02:02

    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:

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

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

    var arr = Object.values(obj);
    

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

    var arr = _.values(obj)
    

提交回复
热议问题