LearnToday
LearnToday

Reputation: 2902

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.

Upvotes: 1

Views: 2050

Answers (2)

nnnnnn
nnnnnn

Reputation: 150010

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, but the only reason to use jQuery for this is if you're supporting IE < 9, because all modern browsers support 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. (The native .map() method doesn't have this "feature".)

Upvotes: 3

Ayan
Ayan

Reputation: 2370

You can solve this without using any library dependency like jquery.

res.push([elem['country'], Number(elem['employ_count'])]);

var arr = [{
  country: "Cameroon",
  employ_count: "58"
}, {
  country: "Germany ",
  employ_count: "50"
}];

function calc(arr) {
  var i,
    len,
    res = [];
  for (i = 0, len = arr.length; i < len; i += 1) {
    elem = arr[i];
    res.push([elem['country'], Number(elem['employ_count'])]);
  }
  return res;
}
console.log(calc(arr));

Upvotes: 1

Related Questions