将jsons附加到vars的问题

时间:2016-06-02 10:48:52

标签: javascript jquery json ajax

所以我让这个json从我的服务器回来了:

[
  [
    "formatted_sum_fees",
    "£6.00"
  ],
  [
    "formatted_price",
    "£60.00"
  ],
  [
    "formatted_sum_fees",
    "£8.00"
  ],
  [
    "formatted_price",
    "£120.00"
  ],
  [
    "formatted_price",
    "£240.00"
  ],
  [
    "formatted_sum_fees",
    "£3.20"
  ],
  [
    "formatted_sum_fees",
    "£2.86"
  ],
  [
    "formatted_sum_fees",
    "£2.50"
  ],
  [
    "ticket_desc",
    "Later Owl Ticket"
  ],
  [
    "ticket_desc",
    "Later Owl Ticket+Collector Ticket &#64 extra £4.95 per ticket"
  ],
  [
    "ticket_desc",
    "Later Owl + Chance For VIP Upgrade"
  ],
  [
    "ticket_desc",
    "VIP Ticket"
  ],
  [
    "ticket_desc",
    "VIP Ticket + Collector Ticket &#64 extra £4.95 per ticket"
  ],
  [
    "ticket_desc",
    "Skydeck Package"
  ],
  [
    "ticket_desc",
    "5 Person Skydeck Table"
  ],
  [
    "ticket_desc",
    "7 Person Skydeck Table"
  ],
  [
    "ticket_desc",
    "10 Person Skydeck Table"
  ]
]

现在我想要的是我的ajax调用将这些放入表中。第一笔费用和价格与第一张ticket_desc相同。每一次!代码我有附加表格代码。 IT将价格,费用和描述纳入变量。我该怎么做呢?

这就是我试图这样做的方式

success: function(json) {
    for (var i = 0; i < json.length; i++) {
      var section = json[i][0];
      if (section == "ticket_desc") {
        var ticket = json[i][1];
        debugger;
      }

但是我遇到了ticket_desc不匹配的问题,但是我觉得它不会起作用!

由于 萨姆

1 个答案:

答案 0 :(得分:0)

我不清楚最终的数据格式应该是什么,并且可能有许多不同的处理你的json的方法,但是试试吧:

我更喜欢具有descriptionfee属性的对象数组。例如:

var ticket = {
  description: "Later Owl Ticket",
  fee: "&Acirc;&pound;6.00"
};

现在,如果我正确理解您的数据,json中数组的 order 将确定费用和描述之间的匹配。

如果是这种情况,并且您可以确定没有缺失值,则可以采用以下简单解决方案:

var nrOfTickets = json.length / 2;
var fees = json.slice(0, nrOfTickets);         // First half
var descriptions = json.slice(nrOfTickets);    // Second half

var tickets = descriptions.map(function(descrArr, index) {
  var feeArr = fees[index];
  return {
    description: descrArr[1],
    fee: feeArr[1]
  };
});

如果你想缩短它,你可以这样做:

var tickets = [];
for (var i = 0, l = json.length / 2; i < l; i += 1) {
  tickets.push({
    fee: json[i][1],
    description: json[i+l][1]
  });
};

如果费用和描述被扰乱,您可以这样排序:

var descriptions = [],
    fees = [];

json.forEach(function(arr) {
  if (arr[1] === "ticket_desc") {
    descriptions.push(arr);
  } else {
    fees.push(arr)
  };
});