Obasi Obeny Oj Obasi Obeny Oj - 4 months ago 105
Javascript Question

How to convert an Object to array using jquery

I have the following object I created from a json file using jquery $.get.
console.log(array);

[Object, Object, Object, Object, Object, Object, Object, Object]
0
:
Object
country
:
"Cameroon"
employ_count
:
50
__proto__
:
Object
1
:
bject
7
:
Object
length:8
__proto__
:
Array[0]


I am trying to convert each object to an array of this type ['Cameroon', 58], ['Germany', 58]....

I tried using jquery $.makeArray

var array = $.makeArray(emObj);


but this still returns an object.

Answer

If I understand you correctly, your input is an array of objects, and your desired output is an array of arrays. This is easy with jQuery's $.map() method, or just the native Array.prototype.map() method:

var input = {
  "countries": [
    { "country": "Australia", "employ_count": 22 },
    { "country": "Cameroon", "employ_count": 50 },
    { "country": "Germany", "employ_count": 13 }
  ]
};

var output = input.countries.map(function(v) { 
  return [v.country, v.employ_count];
});

var outputWithjQuery = $.map(input.countries, function(v) { 
  return [[v.country, v.employ_count]];
});

console.log(output);
console.log(outputWithjQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Note that the double [[ ... ]] in the jQuery version is not a typo: if you return an array from the $.map() function jQuery will flatten it, and returning an array of one element that is the actual array you want fixes that.

Comments