converting object key value pairs to JSON

I have a javascript object with 6 key value pairs:

My_Type_1:"Vegetable"
My_Type_2:"Fruit"
My_Type_3:"Dessert"

My_Value_1: "Carrot"
My_Value_2: "Apple"
My_Value_3: "Cake"

I want to construct JSON out of the above object such that it generates the following:

[{"Vegetable":"Carrot"},{"Fruit":"Apple"},{"Dessert":"Cake"}]

EDIT:

for (j=0;j<3;j++)
{
    var tvArray = new Array();
    var sType = 'My_Type_'+j+1;
    var sValue = 'My_Value_'+j+1;
    tvArray['Type']  = JSObject[sType];
    tvArray['Value'] = JSObject[sValue];
}

The json.stringify doesn't produce the desired output as listed above.

How do I do this?

Thanks


You need to put parenthesis around j + 1 . What you have now gives you 'My_Type_01' and so on.

var obj = {
    My_Type_1:"Vegetable",
    My_Type_2:"Fruit",
    My_Type_3:"Dessert",

    My_Value_1: "Carrot",
    My_Value_2: "Apple",
    My_Value_3: "Cake"
};

var pairs = [], pair;
for(var j = 0; j < 3; j++) {
   pair = {};
   pairs.push(pair);
   pair[obj['My_Type_' + (j+1)]] = obj['My_Value_' + (j+1)];
}


console.log(JSON.stringify(pairs));
链接地址: http://www.djcxy.com/p/46284.html

上一篇: 如何简化参数的传递

下一篇: 将对象键值对转换为JSON