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.
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.
Share Improve this question edited Mar 9, 2023 at 17:21 Geoffrey Hale 11.4k5 gold badges45 silver badges49 bronze badges asked Dec 15, 2015 at 2:39 qazzuqazzu 4113 gold badges8 silver badges16 bronze badges 2-
Is it possible?
yes – vol7ron Commented Dec 15, 2015 at 2:41 - what should I need to do? – qazzu Commented Dec 15, 2015 at 2:41
3 Answers
Reset to default 5Try 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] });
Object.values(data)
yields
[{user: 1, job: 'call center'}, {user: 2, job: 'programmer'}]
- Your Object creation has poor syntax
- 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];
}