【问题标题】:To push data into nested array and then send that whole data using http post method to API将数据推送到嵌套数组中,然后使用 http post 方法将整个数据发送到 API
【发布时间】:2016-06-21 08:17:39
【问题描述】:

这是我的 json 文件,我想将数据推送到数组 workingSchedules 中的 workingDay(多个数据推送)和 workingHours。

    {
  "data": {
    "id": "string",
    "workingSchedules": [
      {
        "workingDay": "MONDAY",
        "workingHours": [
          {
            "fromTime": 0,
            "toTime": 0
          }
        ]
      }
    ],
    "twentyFourSevenOpen": false
  },
  "dataList": [
    {
      "id": "string",
      "workingSchedules": [
        {
          "workingDay": "MONDAY",
          "workingHours": [
            {
              "fromTime": 0,
              "toTime": 0
            }
          ]
        }
      ],
      "twentyFourSevenOpen": false
    }
  ]
}

我的代码是这样的

<table class="table table-bordered table-hover">
          <tr>
            <th class="col-md-4">Day</th>
            <th class="col-md-4">From time</th>
            <th class="col-md-4">To time</th>
        </tr>
        <tbody>

       <form class="form-horizontal" role="form" ng-repeat="x in something.workingSchedules">
              <div class="form-group">

                 <div class="col-sm-4">  
                     <input style="margin-top:15px" ng-model="x.workingDay" class="form-control input-sm" id="pwd" placeholder="Timings">
                 </div>
              </div>
          <form class="form-horizontal" role="form" ng-repeat="x in x.workingHours">

              <div class="form-group">
                 <div class="col-sm-4" >  
                     <input ng-model="x.fromTime" class="form-control input-sm" id="pwd" placeholder="Timings">
                 </div>
              </div>

              <div class="form-group">
                 <div class="col-sm-4">  
                     <input ng-model="x.toTime" class="form-control input-sm" id="pwd" placeholder="Timings">
                 </div>
              </div>

           </form>
         </form>

   </tbody>

这只允许更新单个 workingSchedules 对象,我想要的是首先将数据推送到 UI 中的数组中,然后使用 http post 将其发布到后端 API。

【问题讨论】:

标签: javascript html arrays angularjs json


【解决方案1】:

首先,workingDays 需要是一个数组,就像 workingHours 一样。

完成此操作后,您可以使用以下内容:

data.workingSchedules.workingDay.push('FRIDAY') ;

一般来说,我建议数组中的对象始终采用以下形式:

{"DayName":"MONDAY"}

而不仅仅是当天的名称。不过,您当前的表单可以使用。

【讨论】:

  • 如果是单个数组,他可以这样推data.workingSchedules.workingDay.push("FRIDAY") ;吗?
  • 使用数字来表示工作日肯定比字符串更好吗?例如,在 JS 中尝试执行 new Date().getDay(),这将在今天返回 2,因为它是星期二。
  • @A.Rossi,答案是肯定的。这只是个人喜好问题(如您所知,您编写了一次代码,但您阅读了数百万次,有时甚至在您编写后很长时间,因此请稍加努力使其可读和可维护)。至于使用数字,您需要记住 0 表示“SUNDAY”,或者“MONDAY”,或者 1 表示“SUNDAY”......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-07
  • 2020-04-12
  • 1970-01-01
  • 2019-02-17
  • 1970-01-01
  • 2016-03-19
相关资源
最近更新 更多