close

// Transform JS object to an array
var array = $.map(myObj, function(value, index){
        return [value];
});

--

轉自 https://www.tutorialrepublic.com/faq/how-to-convert-a-js-object-to-an-array-using-jquery.php

--

 

Answer: Use the jQuery $.map() Method

 

You can simply use the $.map() method to convert a JavaScript object to an array of items.

The $.map() method applies a function to each item in an array or object and maps the results into a new array. Let's take a look at an example to understand how it basically works:

 

  • <script>
  •     var myObj = {
  •         name: "Peter",
  •         age: 28,
  •         gender: "Male",
  •         email: "peterparker@mail.com"
  •     };
  •     
  •     // Converting JS object to an array
  •     var array = $.map(myObj, function(value, index){
  •         return [value];
  •     });
  •     
  •     console.log(array);
  •     // Prints: ["Peter", 28, "Male", "peterparker@mail.com"]
  • </script>

 

Let's check out one more example where an object is converted into an array of array:

 

  • <script>
  •     var myObj = {
  •         1: ["Peter", "24"],
  •         2: ["Harry", "16"],
  •         3: ["Alice", "20"]
  •     };
  •     
  •     // Transform JS object to an array
  •     var array = $.map(myObj, function(value, index){
  •         return [value];
  •     });
  •     
  •     console.log(array);
  •     // Output: [["Peter", "24"], ["Harry", "16"], ["Alice", "20"]]
  • </script>

 

See the tutorial on JavaScript objects to learn more about creating and using the objects.

 


Related FAQ

 

Here are some more FAQ related to this topic:

 

 

--

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 dizzy03 的頭像
    dizzy03

    碎碎念

    dizzy03 發表在 痞客邦 留言(0) 人氣()