Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
107
rated 0 times [  108] [ 1]  / answers: 1 / hits: 17856  / 11 Years ago, mon, october 7, 2013, 12:00:00

I need to convert this json object:



forms:
{
Circle:
{
color : red,
size : 1
},
Square:
{
color : blue,
size : 3
},
triangle:
{
color : black,
size : 4
}
}


Into an javascriptArray.
The array should contain formType, color and size.
I have created the following script



var formsArr=[]; 
$.each(forms, function(i, obj){ var form={color: obj.color, size: obj.size};
formsArr.push(form);


The array only contains color and size. I want it to also containt formType ie. Circle, how can I get the key?


More From » jquery

 Answers
40

Here's a way to do it:



var forms = {
Circle: {
color : red,
size : 1
},
Square: {
color : blue,
size : 3
},
triangle: {
color : black,
size : 4
}
};

var result = Object.keys(forms).map(function(key) {
return { type: key, color: this[key].color, size: this[key].size };
}, forms);


With jQuery:



var result = $.map(forms, function(val, key) {
return { type: key, color: val.color, size: val.size };
});

[#75181] Saturday, October 5, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
yaquelina

Total Points: 517
Total Questions: 101
Total Answers: 96

Location: Egypt
Member since Tue, Jul 6, 2021
3 Years ago
yaquelina questions
;