如何在Angularjs中创建嵌套的json对象

时间:2015-08-06 05:07:53

标签: javascript json angularjs

我想在angularjs中创建嵌套的json对象。我的目标是:

   {
    "marketerId": 1,
     "baskets": [
      {
        "customer": {
           "phone": ""
         },
        "region": 1,
        "orders": [
         {
           "bookId": 1,
           "count": 5
         },
         {
           "bookId": 2,
           "count": 52
         }
      ]
   },
    {
      "customer": {
          "phone": ""
     },
      "region": 1,
    "orders": [
     {
        "bookId": 1,
        "count": 12
     },
     {
        "bookId": 2,
        "count": 2
      }
     ]
   }
 ]
}

为了动态创建此对象,我编写此代码。已经初始化了订单和项目,创建了表单。例如,项目和订单的大小2.是否有更好的方法来构建嵌套的json对象?

     <input ng-model="formData.marketerId" />
    <div class="row" ng-repeat="item in items track by $index">
        <input ng-model="formData.baskets[$index].customer.phone" />
        <input ng-model="formData.baskets[$index].region" />
        <div  ng-repeat="order in orders track by $index">
           <input type="text" ng-model=
            "formData.baskets[$parent.$index].orders[$index].bookId">
             <input type="text" ng-model=
            "formData.baskets[$parent.$index].orders[$index].count">

        </div>
    </div>

1 个答案:

答案 0 :(得分:1)

您可以这样做:

$scope.data1 = [];
var firstObj = new Object();
firstObj.first = "value1";
firstObj.second = "value2";
$scope.encountersData.push(firstObj);

$scope.data2 = [];
var  secondObj= new Object();
secondObj.third = "value3";
secondObj.fourth = "value4";
$scope.data2.push(secondObj);