qazzu
qazzu

Reputation: 411

How to convert nested object to array of objects in javascript

I have a data that the structure is like below:

var data = {
    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.

Upvotes: 6

Views: 22313

Answers (3)

Geoffrey Hale
Geoffrey Hale

Reputation: 11438

Object.values(data)

yields

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

Upvotes: 2

vol7ron
vol7ron

Reputation: 42099

  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];
}

Upvotes: 1

Lucas Rodriguez
Lucas Rodriguez

Reputation: 1203

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] });

Upvotes: 5

Related Questions