I have 2 input text and a button. User can click on add button which would create a new row having both input text as below:
Demo: https://jsfiddle.net/ndk29mvp/3/
You can click on Add again and it would add more key value textboxes.
<tr ng-repeat="m in options">
<td>
<input type="text" name="optionKey_{{$index}}" class="form-control"
ng-model="m.optionText" />
</td>
<td>
<input type="text" name="optionValue_{{$index}}" class="form-control"
ng-model="m.optionValue" />
</td>
</tr>
<button type="button" class="btn btn-primary btn-sm" ng-click="Add()">
<i class="fa fa-plus"></i> Add</button>
So basically I am creating dropdowns text and value using the inputs above.
Below is my controller code:
$scope.options = [];
$scope.Add = function () {
var option = {};
option.optionText = $scope.optionText;
option.optionValue = $scope.optionValue;
$scope.options.push(option);
};
In my save function I want to convert the users selection of text and value and convert them into key, value pairs. So if you run my demo above and see the console output, you would see output as:
(2) [{…}, {…}, {…}]
0: {optionText: "1", optionValue: "11", $$hashKey: "005"}
1: {optionText: "2", optionValue: "22", $$hashKey: "007"}
I want to remove all this optionText, optionvalue etc and just create key value pair, so that I create a json object as:
{
"1": "11",
"2": "22"
}
So I tried the below code for doing so:
$scope.data = [];
_.each($scope.options, function (value) {
$scope.data[value.optionText] = value.optionValue;
});
But $scope.data has the below output:
1: "11"
2: "22"
How can I correctly create my key, value format array.
Sorry if this is something trivial, but somehow I am not getting this through. And I was not sure what to give this a appropriate heading.