0

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

1 Answer 1

1

First of all, in this function:

$scope.newField=function(fieldNameVal) {
    var newfield = {
       cfgValue: fieldNameVal
    };
    $scope.cfg.cfgs.splice(0,0,newfield);
    $scope.$apply();
};

$scope.$apply is not needed. Remove it. Second of all, it is obvious that $scope.cfg.cfgs[i] is not an array but rather an object, so to add a field to it, you would do:

$scope.cfg.cfgs[i].cfgsName = val;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.