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]
]);
Yasel
3,1784 gold badges43 silver badges49 bronze badges
asked Jul 17, 2015 at 19:07
user1049961
2,7469 gold badges40 silver badges69 bronze badges
3 Answers 3
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);
answered Jul 17, 2015 at 19:13
Oleksandr T.
77.6k17 gold badges177 silver badges145 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
maybe this is what you're looking for:
var objectArray = [{"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"}];
// build data array
var dataArray = objectArray.map(function(e) {
var key = Object.keys(e).pop();
return [key,e[key]];
});
// add the headers!
dataArray.unshift(['Country', 'Popularity']);
// pass data to google
var data = google.visualization.arrayToDataTable(
dataArray
);
luck!
answered Jul 17, 2015 at 19:21
Santiago Hernández
5,6762 gold badges28 silver badges34 bronze badges
2 Comments
user1049961
Thanks, this helped a lot!
Santiago Hernández
@user1049961 no problem :P
const arrObj = [{"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 thisArr = [];
const result = arrObj.reduce((acc, thisObj) => {
thisArr = [];
for(let val in thisObj) {
thisArr.push(val)
thisArr.push(thisObj[val])
acc.push(thisArr);
}
return acc;
}, []);
console.log(result)
1 Comment
Community
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
lang-js
SyntaxError:[["CZ-PR":"1"],["CZ-JC":"0"]]