我需要转换这个json对象:
"forms":
{
"Circle":
{
"color" : "red",
"size" : "1"
},
"Square":
{
"color" : "blue",
"size" : "3"
},
"triangle":
{
"color" : "black",
"size" : "4"
}
}
进入javascriptArray。 该数组应包含formType,颜色和大小。 我创建了以下脚本
var formsArr=[];
$.each(forms, function(i, obj){ var form={color: obj.color, size: obj.size};
formsArr.push(form);
该数组仅包含颜色和大小。我希望它也包含formType ie。圈,我怎样才能获得钥匙?
答案 0 :(得分:9)
这是一种方法:
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);
使用jQuery:
var result = $.map(forms, function(val, key) {
return { type: key, color: val.color, size: val.size };
});