Reputation: 411
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
Reputation: 11438
Object.values(data)
yields
[{user: 1, job: 'call center'}, {user: 2, job: 'programmer'}]
Upvotes: 2
Reputation: 42099
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
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