How to change the value of a JSON element.
I have a JSON like this in my controler
$scope.cfg= {
"cfgName" : "Name",
"cfgs": [
{
"cfgsName": "form.0",
"cfgValue": "hello"
},
{
"cfgsName": "form.1",
"cfgValue": "fname"
},
{
"cfgsName": "form.2",
"cfgValue": "how?"
}
]
};
Now I have a method to add one field as first element in cfgs array.
$scope.newField=function(fieldNameVal) {
var newfield={
"cfgValue": fieldNameVal
};
$scope.cfg.cfgs.splice(0,0,newfield);
$scope.$apply();
};
The above is working fine. But I want to change the value of cfgValue of each in the array so that the value looks in order like its index.
The required json string after adding new item is
{
"cfgName": "Name",
"cfgs": [
{
"cfgsName": "form.0",
"cfgValue": "someVal"
},
{
"cfgsName": "form.1",
"cfgValue": "hello"
},
{
"cfgsName": "form.2",
"cfgValue": "fname"
},
{
"cfgsName": "form.3",
"cfgValue": "how?"
}
]
}
I have tried the following code inside newField() method after adding item.
for(var i=0;i<$scope.cfg.cfgs.length;i++) {
var val="engine.form."+i;
$scope.cfg.cfgs[i].push({"cfgsName" : val});
}
But it shows error.
Uncaught TypeError: Object #<Object> has no method 'push'
What is the correct way? Thanks