JavaScript JSON Math-在对象中添加元素

时间:2019-01-20 13:57:51

标签: javascript json math

我什至不知道从哪里开始,因为这个问题有两个部分。第一个是以下内容:

A customer orders two products and the packages are coming from 91324 zip code going to 77096 zip code, with the following dimensions and rates from the UPS API

width 2
height 2
length 2
weight 5
"Next Day Air (early AM)":"68.27",
"Next Day Air":"36.47",
"Next Day Air Saver":"35.40",
"2nd Day Air":"24.92",
"3 Day Select":"16.86",
"Ground":"13.52"

width 2
height 5
length 2
weight 2
"Next Day Air (early AM)":"75.64",
"Next Day Air":"43.84",
"Next Day Air Saver":"41.32",
"2nd Day Air":"26.50",
"3 Day Select":"20.53",
"Ground":"14.29"

以下是JSON的样子:

  {
  "services": 
    [{
      "service": "Next Day Air (early AM)",
      "rate": "68.27"
    }, {
      "service": "Next Day Air",
      "rate": "36.47"
    }, {
      "service": "Next Day Air Saver",
      "rate": "35.40"
    }, {
      "service": "2nd Day Air",
      "rate": "24.92"
    }, {
      "service": "3 Day Select",
      "rate": "16.86"
    }, {
      "service": "Ground",
      "rate": "13.52"
    },
    {
      "service": "Next Day Air (early AM)",
      "rate": "75.64"
    }, {
      "service": "Next Day Air",
      "rate": "43.84"
    }, {
      "service": "Next Day Air Saver",
      "rate": "41.32"
    }, {
      "service": "2nd Day Air",
      "rate": "26.50"
    }, {
      "service": "3 Day Select",
      "rate": "20.53"
    }, {
      "service": "Ground",
      "rate": "14.29"
    }]
}

该场景的第二部分是,客户订购了第一个产品的2个和第二个产品的三个,这由以下JSON表示:

      [{
    "id": "8",
    "name": "Austin to Carls 32 to 33 chocolates to oil",
    "price": "9.67",
    "category": "oils",
    "description": "The standard Lorem Ipsum passage, used since the 1500s Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...",
    "ts": "2019-01-08 11:47:09",
    "product_image_id": "33",
    "enabled": "1",
    "product_image": "crater-winslow-40.png",
    "counter": 2
  }, {
    "id": "27",
    "name": "test 10 jwt",
    "price": "10.56",
    "category": "oils",
    "description": "The standard Lorem Ipsum passage, used since the 1500s Lorem ipsum dolor sit amet, ...",
    "ts": "2019-01-08 09:55:10",
    "product_image_id": "45",
    "enabled": "1",
    "product_image": "ryan-settings.png",
    "counter": 3
  }]

我知道我可能可以执行以下操作:this.shoppingCart.counter [j] * this.upsObj [i] .rates,然后添加各种“ Next Day Air(凌晨AM)”,但是我该怎么做?

最重要的是,必须在this.upsObj中更新新费率,以便最终用户只能看到以下内容:

  "Next Day Air (early AM)":"363.46", // 136.54 (2) + 226.92 (3)
  "Next Day Air":"204.46", // 72.94 (2) + 131.52 (3)
  "Next Day Air Saver":"194.76", // 70.80 (2) + 123.96 (3)
  "2nd Day Air":"129.34", // 49.84 (2) + 79.50 (3)
  "3 Day Select":"95.31", // 33.72 (2) + 61.59 (3)
  "Ground":"69.91" // 27.04 (2) + 42.87 (3)

最后,我从测试UPS API收到的费用似乎太高了,然后,我一次很少购买一件以上的东西,我想任何一家有特殊优惠的公司都在付款。这些数字看起来不是过多吗?

再一次,我真的不知所措,甚至不知道从哪里开始。例如,如果客户添加了第三种产品并想要其中的四种呢?

1 个答案:

答案 0 :(得分:0)

以防万一其他人遇到这种困境,以下是我所做的事情:

  public getUps() {
  const Obj = this.product_id;
  this.countRows = Object.keys(Obj).map(function(key) {
    return [Number(key), Obj[key]];
  });
  console.log("countRows.length: ", this.countRows.length);
  for (let v = 0; v < this.countRows.length; v++) {
    this.upsRateUrl =
      this.loginSrvc.serverBase +
      "<someUrl>?id=" +
      this.product_id[v] +
      "&tozip=" +
      this.model.zip;

    this.http.get(this.upsRateUrl).subscribe(resultUps => {
      this.service.push(resultUps);
      // make json compatible with Angular ngFor
      this.tempUpsObj = JSON.stringify(this.upsObj);
      this.tempUpsObj = this.tempUpsObj.replace(/\[\[/gi, "[");
      this.tempUpsObj = this.tempUpsObj.replace(/\]\]/gi, "]");
      this.tempUpsObj = this.tempUpsObj.replace(/\}\]\,\[\{/gi, "},{");
      // return it to an object
      this.copyUpsObj = JSON.parse(this.tempUpsObj);
      this.combineAndCalculateRate();
    });
  }
  this.upsObj = {
    services: this.service
  };
  this.upsComplete = true;
}

public combineAndCalculateRate() {
  this.combineUpsObj = JSON.parse(this.tempUpsObj);
  // this.countRows.length are the number of products
  this.divisNums = [];
  // make array of divisible numbers
  for (let s = 1; s <= this.combineUpsObj.services.length; s++) {
    if (s % 6 === 0) {
      this.divisNums.push(s);
    }
  }
  console.log("divisNums: ", this.divisNums);
  let w = 0;
  for (let c = 0; c < this.combineUpsObj.services.length; c++) {
    if (c === this.divisNums[w]) {
      w++;
    }
    // multiple by how many of each product
    this.combineUpsObj.services[c]["rate"] =
      this.combineUpsObj.services[c]["rate"] *
      this.prdSrvc.cartObj.cart.products.product[w].counter;

  }
  let z = 0;
  for (let f = 0; f < 6; f++) {
    this.combineAddIntoOneObj.services[f]["rate"] = 0;
  }
  for (let e = 1; e <= this.product_id.length; e++) {
    for (let d = 0; d < 6; d++) {
      this.combineAddIntoOneObj.services[d][
        "rate"
      ] += this.combineUpsObj.services[z]["rate"];
      // trying to avoid undefined, but console still shows one error
      if (z < this.combineUpsObj.services.length) {
        z++;
      }
    }
  }

  this.tempUpsObj = this.combineAddIntoOneObj;
  console.log("this.combineAddIntoOneObj: ", this.combineAddIntoOneObj);
}

console showing the newly created object

以下是Angular html:

   <hr class="mb-4" />
    <div class="col">
      <div class="row">
        <div class="col">
          <div class="card product-card">
            <div class="card-body">
              <h5 class="card-title">UPS</h5>
              <label for="ups"
                ><input
                  type="checkbox"
                  name="upsCheckBox"
                  (click)="this.getUps()"
                /><span
                  *ngIf="
                    this.upsChecked &&
                      !this.payPalSrvc.upsObj.services.length > 0;
                    else upsDone
                  "
                  >Retrieving rates from UPS...
                  <img src="../../assets/images/ajax-loader.gif" />
                </span>
                <ng-template #upsDone>
                  <select
                    class="custom-select d-block w-100"
                    [(ngModel)]="model.ups"
                    name="ups"
                    id="ups"
                    #ups="ngModel"
                    required
                  >
                    <option value="" selected="selected"
                      >UPS delivery service</option
                    >
                    <option
                      *ngFor="
                        let ups of this.payPalSrvc.combineAddIntoOneObj
                          .services;
                        let i = index
                      "
                      value="{{ ups.service + ' - ' + ups.rate }}"
                      >{{ ups.service + " - " + ups.rate }}</option
                    >
                  </select>
                </ng-template>
              </label>
            </div>
            <div class="card-footer"></div>
          </div>
        </div>
      </div>
    </div>

Angular drop down menu