根据数组值的顺序,如何适当地映射JSON值?

时间:2014-11-11 15:09:23

标签: jquery

我有这种格式的JSON

var orderjson = 
    {
        "display": {
            "ServiceCharge": "1",
            "ServiceTax": "2",
            "order": [
                "ServiceCharge",
                "ServiceTax",
                "VAT",
                "DISCOUNT",
                "OTHERS"
            ],
            "VAT": "3",
            "OTHERS": "4",
            "DISCOUNT": "5"
        }
    }

我正在提取如下所示的订单,但无法正确映射

这是我的程序

var orderOfDisplay = orderjson.display.order;

var ServiceCharge = orderjson.display.ServiceCharge;
var ServiceTax = orderjson.display.ServiceTax;
var VAT = orderjson.display.VAT;
var OTH1 = orderjson.display.OTH1;
var DISCOUNT = orderjson.display.DISCOUNT;

var htmldata =  '';

for(var i=0;i<orderOfDisplay.length;i++)
{
     htmldata+= '<tr><td align="right" valign="middle" width="50%">'+orderOfDisplay[i]+'</td> \
    <td align="right" valign="middle" width="50%">Rs. '+ServiceCharge+'</td> \
    </tr>';


}

http://jsfiddle.net/2kbet2hL/1/

你能帮我吗

我的预期输出

ServiceCharge   Rs. 1
ServiceTax  Rs. 2
VAT                   Rs. 3
DISCOUNT    Rs. 5
OTHERS                     Rs. 4

2 个答案:

答案 0 :(得分:1)

只需更改htmldata

ServiceCharge

为:

orderjson.display[orderOfDisplay[i]]

编辑然后不再需要所有变量ServiceCharge, ServiceTax, VAT, OTHERS, DISCOUNT

答案 1 :(得分:0)

我希望这可能是您的预期结果

for(var i=0;i<orderOfDisplay.length;i++)
{
     htmldata+= '<tr><td align="right" valign="middle" width="50%">'+orderOfDisplay[i]+'</td> ';
     if(orderOfDisplay[i]=="OTHERS"){
         orderOfDisplay[i]="OTH1";
     }
   htmldata+=' <td align="right" valign="middle" width="50%">Rs. '+orderjson.display[orderOfDisplay[i]]+'</td> \
    </tr>';


}