obj = {'a':['hello', 'hie'], 'b':['World', 'India']}
To
array = [{'a':'hello','b':'World'}, {'a':'hie','b':'India'}]
Best way to convert this or any build-in method for this conversion using JQuery.
asked Nov 28, 2012 at 11:42
-
9"Best way to convert this or any build-in method for this conversion using JQuery." Write code looping through the properties of the object and building up the result. There isn't a shortcut.T.J. Crowder– T.J. Crowder2012年11月28日 11:42:49 +00:00Commented Nov 28, 2012 at 11:42
-
Your mapping isn't that well defined. Please provide a few more examples and/or elaborate.user1726343– user17263432012年11月28日 11:50:58 +00:00Commented Nov 28, 2012 at 11:50
-
1jQuery, now fabled as the Universal Swiss Army Knife of Web development... :-)PhiLho– PhiLho2012年11月28日 11:51:21 +00:00Commented Nov 28, 2012 at 11:51
2 Answers 2
Try this Code,
obj = {'a':['hello', 'hie'], 'b':['World', 'India']}
var key = Object.keys(obj);
array = [];
for (var i = 0; i < obj['a'].length; i++){
o = {}
for (k in key){
o[key[k]] = obj[key[k]][i]
}
array.push(o)
}
answered Nov 28, 2012 at 11:53
user1591822user1591822
Sign up to request clarification or add additional context in comments.
1 Comment
Bergi
Don't use a for-in-loop for the
key
array. Also, some semicolons would be nice.var obj = {'a':['hello', 'hie'], 'b':['World', 'India']};
var array = [];
for (var prop in obj)
for (var i=0; i<obj[prop].length; i++) {
var o = array[i] || (array[i] = {});
o[prop] = obj[prop][i];
}
No jQuery needed. With jQuery, it might look like this:
var array = [];
$.each(obj, function(prop) {
$.each(this, function(i) {
var o = array[i] || (array[i] = {});
o[prop] = this;
});
});
- slower and less readable. Do not use.
answered Nov 28, 2012 at 12:02
Comments
lang-js