Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

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 };
});
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.