Converting a JS object to an array using jQuery

后端 未结 18 3366
鱼传尺愫
鱼传尺愫 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:04

    If you want to keep the name of the object's properties as values. Example:

    var fields = {
        Name: { type: 'string', maxLength: 50 },
        Age: { type: 'number', minValue: 0 }
    }
    

    Use Object.keys(), Array.map() and Object.assign():

    var columns = Object.keys( fields ).map( p => Object.assign( fields[p], {field:p} ) )
    

    Result:

    [ { field: 'Name', type: 'string', maxLength: 50 }, 
      { field: 'Age', type: 'number', minValue: 0 } ]
    

    Explanation:

    Object.keys() enumerates all the properties of the source ; .map() applies the => function to each property and returns an Array ; Object.assign() merges name and value for each property.

提交回复
热议问题