将键和值都动态地推入json数组结构中

时间:2017-03-03 08:55:49

标签: javascript angularjs json

我的angularjs前端代码如下:



function addController($scope, $http) {
  $scope.tableNames = [];
  $scope.addNewColumn = function(item) {
    $scope.tableNames.push({})
  }
}

<html ng-app>
<head>
  <title></title>
  <meta charset="utf-8" />
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>
<body ng-controller="addController">
  <div class="col-sm-10">

    <fieldset ng-repeat="item in tableNames track by $index">
      <span> TextBox1:<input type="text" ng-model="item.item1" />
          TextBox2:<input type="text" ng-model="item.item2" /></span>

    </fieldset>
    <button class="btn btn-default" ng-click="addNewColumn()">Add Colname</button>
  </div>
  <pre>{{tableNames|json}}</pre>
</body>
</html>
&#13;
&#13;
&#13;

因此,当我在textbox1和textbox2中输入文本时,它会显示以下格式的数组:

[{
"item1":"textbox1value",
"item2":"textbox2value"
}]

当我点击addColname按钮并生成另一个文本框时,值会被推送到不同的属性中,如下所示,它会生成:

[{
"item1":"textbox1value",
"item2":"textbox2value"
},
{
"item1":"textbox1value",
"item2":"textbox2value"
}
]

但实际上我需要的是结构,

[{
"textbox1value":"textbox2value",
"textbox1value":"textbox2value",
.....
}]

note(:"textboxvalue"是在文本框中输入的值。

有人帮助我获得所需的输出。提前谢谢

1 个答案:

答案 0 :(得分:0)

这是一个有效的代码。我希望这会有所帮助:)

<html ng-app>
<head>
<title></title>
<meta charset="utf-8" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script>
    function addController($scope, $http) {

        $scope.tableNames = []; 
        $scope.getData={};
        var i=-1;

        $scope.addNewColumn = function (item) {
            $scope.tableNames.push({})
            i++;
        }
        $scope.addData = function(item){
            if(i >= 0){ 
                $scope.newData=[];
      $scope.getData[$scope.tableNames[i].item1]=$scope.tableNames[i].item2;
                $scope.newData.push($scope.getData);
        }
    }


}  

</script>
</head>
<body ng-controller="addController">      
<div class="col-sm-10">

    <fieldset ng-repeat="item in tableNames track by $index">
        <span> TextBox1:<input type="text" ng-model="item.item1" ng-keyup="addData()"/>
      TextBox2:<input type="text" ng-model="item.item2" ng-keyup="addData()"/></span>

    </fieldset>
    <button class="btn btn-default" ng-click="addNewColumn()">Add Colname</button>

</div>
    <pre>{{newData|json}}</pre>


</body>
</html>