JS - converts objects to array

user1049961

I have following array of objects:

[{"CZ-PR":"1"},{"CZ-JC":"0"},{"CZ-JM":"0"},{"CZ-KA":"0"},{"CZ-VY":"0"},{"CZ-KR":"0"},{"CZ-LI":"0"},{"CZ-MO":"0"},{"CZ-OL":"0"},{"CZ-PA":"0"},{"CZ-PL":"0"},{"CZ-ST":"0"},{"CZ-US":"0"},{"CZ-ZL":"0"}]

I need to convert it to array of arrays, like this (need to pass it to Google Maps Geocharts constructor):

[["CZ-PR","1"],["CZ-JC","0"]]

I tried:

var arr = [];
for (var k in obj) arr.push([+k, obj[k]]);

Which gives me array for each letter... How can I convert my initial object to what I need?

EDIT: The format that is expected from Google geocharts is this:

var data = google.visualization.arrayToDataTable([
      ['Country', 'Popularity'],
      ['Germany', 200],
      ['United States', 300],
      ['Brazil', 400],
      ['Canada', 500],
      ['France', 600],
      ['RU', 700]
    ]);
Oleksandr T.

Try this

var data = [{"CZ-PR":"1"},{"CZ-JC":"0"},{"CZ-JM":"0"},{"CZ-KA":"0"},{"CZ-VY":"0"},{"CZ-KR":"0"},{"CZ-LI":"0"},{"CZ-MO":"0"},{"CZ-OL":"0"},{"CZ-PA":"0"},{"CZ-PL":"0"},{"CZ-ST":"0"},{"CZ-US":"0"},{"CZ-ZL":"0"}];

var result = [];

result = data.map(function (el) {
    var key = Object.keys(el).pop()

    return [
        key, +el[key]
    ]
});

console.log(result);

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related