1

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

Jake
  • 25,479
  • 31
  • 107
  • 168

1 Answers1

1

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));
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98