How to convert nested object to array of objects in javascript

I have a data that the structure is like below:

var data = Object {
    0 = {
        user : 1
        job  : call center
    },
    1 = {
        user : 2
        job  : programmer
    }
}

Now I want to convert them to array of objects that looks like this:

[Object {user : 1, job  : call center}, {user : 2, job  : programmer} ]

Is it possible? How can I convert them. Any help, thanks.

Answers:

Answer
  1. Your Object creation has poor syntax
  2. Below shows you how to do this with a simple for loop, but makes a lot of assumptions (e.g., your object keys are labeled correctly). I would ordinarily use map, but feel that may not be as easy/straightforward for you to understand; so the loop should be simple enough to follow.

var data =  { 0:{
                  user : 1,
                  job  : 'call center'
              },
              1:{
                  user : 2,
                  job  : 'programmer'
              }
            };


var arr  = [],
    keys = Object.keys(data);

for(var i=0,n=keys.length;i<n;i++){
  var key  = keys[i];
  arr[key] = data[key];
}
Answer

Try using map

 var array = $.map(data , function(value, index) {
     return [value];
 });

You can also do it without jQuery:

var array = Object.keys(data).map(function(k) { return obj[k] });

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.