4

我需要转换这个 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 即。圈子,我怎样才能得到钥匙?

4

1 回答 1

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 };
});
于 2013-10-07T07:58:44.787 回答