0

I have a JSON object, from which I want to get the output like this and console.log into browser.

FROM: Frontier WHSE, TO: ENTEC POLYMERS

JSON object to traverse:

 {
    "loadStops": [{
        "id": 1,
        "type": "FROM",
        "stop": {
            "companyId": 148,
            "companyCode": "FWS",
            "legalName": "Frontier WHSE"
        }
    }, {
        "id": 2,
        "type": "TO",
        "stop": {
            "companyId": 151,
            "companyCode": "ENP",
            "legalName": "ENTEC POLYMERS"
        }
    }]
}

I tried this but didn't work exactly:

var from = "";
var to = "";
var summary = "";

angular.forEach( object, function() {

    if( key == "type" && value == "FROM" ) {
        from +=value;
    }

    if( key == "type" && value == "TO" ) {
        to+=value;
    }

});

summary += from + to;
1
  • 1
    are you sure that you want an array of objects (with "FROM" and "TO")? you can try to format it if you know the order in which they come in (by index): console.log(`FROM: ${json.loadStops[0].stop.legalName} WHSE, TO: ${json.loadStops[1].stop.legalName}`) Commented Feb 22, 2018 at 13:32

1 Answer 1

1

DEMO

var app = angular.module('testApp',[])

app.controller('testCtrl',function($scope){
 $scope.data = 
 {
"loadStops": [{
    "id": 1,
    "type": "FROM",
    "stop": {
        "companyId": 148,
        "companyCode": "FWS",
        "legalName": "Frontier WHSE"
    }
}, {
    "id": 2,
    "type": "TO",
    "stop": {
        "companyId": 151,
        "companyCode": "ENP",
        "legalName": "ENTEC POLYMERS"
    }
}]};
var summary = "";
$scope.print = function(){
angular.forEach($scope.data.loadStops,function(key,value){
    if(key.type == "FROM"){
       summary = "FROM :" + key.stop.legalName;
    }
    if(key.type == "TO"){
      summary += " TO :" + key.stop.legalName;
    }
   
});
return summary;
};

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="testApp" ng-controller="testCtrl">
  <h1>{{print()}}</h1>
</div>

Sign up to request clarification or add additional context in comments.

2 Comments

I think summary = "FROM ... should have +=
what? edit your code? (I only mentioned it because if you have more that once case of "FROM" types, you will overwrite summary)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.