首页 > 解决方案 > json wihin multiple loop issue on basis of id

问题描述

I'm getting data from third-party API.

From the first loop, I'm getting all the bookings data. and within a loop, I want to get booking detail of each booking id.

But when I'm trying to create an array and trying to push into the JSON. it is looping for the length of booking detail and multiply with the main loop and getting whole data to the last JSON created.

But I need only booking id data for each id not whole data to the last booking id.

Can you please help me to resolve the issue.

Here is my script:

jQuery.each(bookings, function(index, val) {

  var bookingDetails = client.getBookingDetails(bookings[index].id);

  jQuery.each(bookingDetails.additional_fields, function(i, fields) {
    var id = fields.field_id;
    var value = fields.value;
    arr.push({
      id,
      value
    });
    xy = JSON.stringify(arr);
  });

  dataItems += '{"booking_id"' + ": " + bookings[index].id + "," + '"booking_service"' + ": " + '"' + bookings[index].event + '"' + "," + '"booking_area"' + ": " + '"' + bookings[index].unit + '"' + "," + '"booking_stid"' + ": " + '"' + bookings[index].code + '"' + "," + '"booking_scid"' + ": " + '" "' + "," + '"booking_day"' + ": " + '"' + lesson_day + '"' + "," + '"booking_time"' + ": " + '"' + lesson_time + '"' + "," + '"booking_tname"' + ": " + '" "' + "," + '"booking_tgname"' + ": " + '" "' + "," + '"booking_bookdate"' + ": " + '"' + lesson_day + '"' + "," + '"booking_rpid"' + ": " + '" "' + "," + '"booking_rpaddress"' + ": " + '" "' + "," + '"booking_sub"' + ": " + '" "' + "," + '"booking_pcode"' + ": " + '" "' + "," + '"booking_wphone"' + ": " + '" "' + "," + '"booking_mphone"' + ": " + '" "' + "," + '"booking_mail"' + ": " + '" "' + "," + '"booking_state"' + ": " + '"  "' + "," + '"booking_gender"' + ": " + '" "' + "," + '"booking_dob"' + ": " + '" "' + "," + '"additional_fields"' + ": " + xy + "},";
});

apidata = dataItems;
apidata = dataItems.substring(0, dataItems.length - 1);
apidata = "[" + apidata + "]";
});

标签: javascriptjqueryjsonmultidimensional-array

解决方案


forEach您可以通过使用来迭代数组和使用backticks来创建多行字符串来重构您的代码。

这里的错误可能与使用索引变量来 fetch 有关additional_fields。请在下面找到重构的代码。

(function($) {
  var JSONRpcClientException = function(code, message) {
    this.code = code;
    this.message = message;
  }

  JSONRpcClientException.prototype = jQuery.extend(JSONRpcClientException.prototype, {

    /**
     * Magic method. COnvert object to string.
     * 
     * @return String
     */
    toString: function() {
      return '[' + this.code + '] ' + this.message;
    }
  });

  /**
   * JSON-RPC Client
   * 
   * @param Object options
   */
  var JSONRpcClient = function(options) {
    this.setOptions(options);
    this.init();
  }
  JSONRpcClient.prototype = jQuery.extend(JSONRpcClient.prototype, {

    /**
     * Default options
     */
    options: {
      'onerror': function() {},
      'onsuccess': function() {},
      'url': '',
      'headers': {}
    },
    current: 1,
    onerror: null,
    onsuccess: null,
    onstart: null,

    /**
     * Init client
     */
    init: function() {
      this.onerror = this.getParam('onerror');
      this.onsuccess = this.getParam('onsuccess');

      this.initMethods();
    },

    /**
     * Init API methiods by url
     */
    initMethods: function() {
      var instance = this;
      // get all methods
      jQuery.ajax(this.getParam('url'), {
        'async': false,
        'success': function(data) {
          if (data.methods) {
            // create method
            jQuery.each(data.methods, function(methodName, methodParams) {
              var method = function() {
                var params = new Array();
                for (var i = 0; i < arguments.length; i++) {
                  params.push(arguments[i]);
                }
                var id = (instance.current++);
                var callback = params[params.length - 1];
                var request = {
                  jsonrpc: '2.0',
                  method: methodName,
                  params: params,
                  id: id
                };

                var async = false;
                if (jQuery.type(callback) == 'function') {
                  async = true;
                  params.pop();
                }

                var res = null;
                // API request
                jQuery.ajax(instance.getParam('url'), {
                  'contentType': 'application/json',
                  'type': methodParams.transport,
                  'processData': false,
                  'dataType': 'json',
                  'cache': false,
                  'data': JSON.stringify(request),
                  'headers': instance.getParam('headers'),
                  'async': async,
                  'success': function(result) {
                    if (jQuery.type(result.error) == 'object') {
                      res = new JSONRpcClientException(result.error.code, result.error.message);
                      instance.onerror(res);
                    } else {
                      res = result.result;
                      if (jQuery.type(callback) == 'function') {
                        callback(res);
                      }
                    }
                    instance.onsuccess(res, id, methodName);
                  }
                });
                if (!async) {
                  return res;
                }
              }

              instance[methodName] = method;
            });
          } else {
            throw Exception("Methods could not be found");
          }
        }
      });
    },

    /**
     * Set client options
     * 
     * @param Object options
     */
    setOptions: function(options) {
      this.options = jQuery.extend({}, this.options, options);
    },

    /**
     * Get client param, if param is not available in this.options return defaultValue
     * 
     * @param String key
     * @param mixed defaultValue
     * @return mixed
     */
    getParam: function(key, defaultValue) {
      if (jQuery.type(this.options[key]) != 'undefined') {
        return this.options[key];
      }
      return defaultValue;
    }

  });

  var loginClient = new JSONRpcClient({
    'url': 'https://user-api.simplybook.me' + '/login',
    'onerror': function(error) {},
  });
  var token = loginClient.getUserToken("skateclub", "admin", "TonyHawk");
  var company_login = "skateclub";

  client = new JSONRpcClient({
    'url': 'https://user-api.simplybook.me' + '/admin/',
    'headers': {
      'X-Company-Login': company_login,
      'X-User-Token': token
    },
    'onerror': function(error) {}
  });

  //var bookings = client.getBookings({"date_from":"2015-01-01"});
  //var bookings = client.getBookingsZapier(10);
  var bookings = client.getBookings({
    "date_from": "2019-09-10",
    "date_to": "2019-09-13"
  });

  jQuery(document).ready(function() {
    var inc = 0,
      bx = 0;
    var dataItems = "";
    var bookItems = "";
    var bookData = "";
    var apidata = "";
    var newBookData = "";
    var arr = [];
    var xy = [];
    var z = "";

    bookings.forEach(bookingDetails => {
      additional_fields = client.getBookingDetails(bookingDetails.id).additional_fields;
      /* Lesson Date Time */
      var DayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
      var start_date = new Date(bookings.start_date);
      var lesson_day = DayNames[start_date.getDay()];
      var cHour = start_date.getHours();
      var cMin = start_date.getMinutes();

      if (cMin < 10)
        cMin = "0" + cMin;

      var suffix = "AM";
      if (cHour >= 12) {
        suffix = "PM";
        cHour = cHour - 12;
      }
      if (cHour == 0) {
        cHour = 12;
      }
      var lesson_time = cHour + ":" + cMin + " " + suffix;
      xy = [];
      additional_fields.forEach(item => {
        xy.push({
          b_id: bookingDetails.id,
          field_id: item.field_id,
          value: item.value
        });
      });
      dataItems += `'booking_id : ${bookingDetails.id}, additional_fields : ${JSON.stringify(xy)}`;
    });
    apidata = dataItems;
    apidata = dataItems.substring(0, dataItems.length - 1);
    apidata = "[" + apidata + "]";
    console.log(apidata);
  });


})(jQuery);
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>


推荐阅读