如何在AngularJs中将JSON对象推送到数组

时间:2016-08-01 14:02:08

标签: angularjs

需要将JSON对象推送到角度JS并且需要检查之前是否存在其中一个对象的值我需要覆盖数据,

$scope.setData = function(survey, choice) {

  keepAllData.push({
    'surveyId': survey.id,
    'choiceId': choice.id
  });
  console.log(keepAllData);
  toArray(keepAllData);
  alert(JSON.stringify(toArray(keepAllData)));

  $scope.keepAllDatas.push({
    'surveyId': survey.id,
    'choiceId': choice.id
  });
  var items = ($filter('filter')(keepAllDatas, {
    surveyId: survey.id
  }));

}

function toArray(obj) {
  var result = [];
  for (var prop in obj) {
    var value = obj[prop];
    console.log(prop);
    if (typeof value === 'object') {
      result.push(toArray(value));

      console.log(result);
    } else {
      result.push(value);
      console.log(result);
    }
  }
  return result;
}

如果调查ID存在于keepalldata中,则需要使用choiceid更改最近的值。请让我知道是否可以使用angular JS

2 个答案:

答案 0 :(得分:1)

尝试这样做:在推送数据之前,您必须检查调查ID是否存在,如果存在,您必须使用相应的调查ID更新选择,否则您可以直接推送。

<?xml version='1.0' encoding='UTF-8'?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP-ENV:Header>
        <wsse:Security
            xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
            SOAP-ENV:mustUnderstand="1">
            <wsse:UsernameToken
                xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
                xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
                wsu:Id="uuid_86c8ee4f-b6e6-4e07-9fa6-e2f9f2695c01">
                <wsse:Username>admin</wsse:Username>
                <wsse:Password
                    Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">mx9483</wsse:Password>
            </wsse:UsernameToken>
        </wsse:Security>
    </SOAP-ENV:Header>
    <SOAP-ENV:Body>
    <paes:IdName>CancelId</paes:IdName>
    <paes:IdValue>2786872</paes:IdValue>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

DEMO

答案 1 :(得分:0)

 $scope.keepAllDatas = [];
 $scope.setData = function(survey,choice) {

            if($scope.keepAllDatas.length == 0) {
            $scope.keepAllDatas.push({'surveyId':survey.id,'choiceId':choice.id});
           }
           else{
            var items = ($filter('filter')( $scope.keepAllDatas, {surveyId: survey.id }));
            for (var i = items.length - 1; i >= 0; i--) {
               // alert(items[i].surveyId);
               if(items[i].surveyId == survey.id) {
                console.log($scope.keepAllDatas.indexOf(survey.id));
                  $scope.keepAllDatas.splice($scope.keepAllDatas.indexOf(survey.id),1);
                  console.log("Removed data")
               }
            }
             $scope.keepAllDatas.push({'surveyId':survey.id,'choiceId':choice.id});
             console.log( $scope.keepAllDatas)
            // alert(items[0].surveyId);
          }

        }