1
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
3
  • 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. Commented Nov 28, 2012 at 11:42
  • Your mapping isn't that well defined. Please provide a few more examples and/or elaborate. Commented Nov 28, 2012 at 11:50
  • 1
    jQuery, now fabled as the Universal Swiss Army Knife of Web development... :-) Commented Nov 28, 2012 at 11:51

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Don't use a for-in-loop for the key array. Also, some semicolons would be nice.
1
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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.