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.

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... :-)
    – PhiLho
    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)
}
1
  • 1
    Don't use a for-in-loop for the key array. Also, some semicolons would be nice.
    – Bergi
    Commented Nov 28, 2012 at 12:46
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.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.