0

I have a json object, but want to format the output into a variable.

var json =  [
   {
      "link-params": {
         "location_id": 1
      },
      "link-text": "United States"
   },
   {
      "link-params": {
         "location_id": 9
      },
      "link-text": "Florida"
   }
]

 for(var i = 0; i < json.length; i++) {
   var data = json[i]['link-text'];
 }

//output United States / Florida

I want the output like United States / Florida

Any idea how you do this in javascript? I am using angular.js

2
  • " str2.concat(str1) " function use Commented May 19, 2016 at 5:53
  • access JSON object with json["link-text"] and concatenate them. Commented May 19, 2016 at 5:55

4 Answers 4

1

please try this

data='';
for(var i = 0; i < json.length; i++) {
   var str1 =  json[i]['link-text'];
   if(i !== json.length - 1) str1 += ' / ';
   data = data.concat(str1)
 }
Sign up to request clarification or add additional context in comments.

1 Comment

The desired output is United States / Florida, while the above code output will be United States/Florida/
0

try this

var myApp = angular.module('myApp',[]);

function DetailCtrl($scope) {
  $scope.json =  [
   {
      "link-params": {
         "location_id": 1
      },
      "link-text": "United States"
   },
   {
      "link-params": {
         "location_id": 9
      },
      "link-text": "Florida"
   }
];
  var data = [];
  var item = "";
  angular.forEach($scope.json,function(value,key){
         angular.forEach(value,function(v,k){
             if(k == "link-text")
               item = item +v+"/";
           });
            
      });
  data.push(item);
 console.log(data);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="DetailCtrl">
  
</div>

1 Comment

How would I access this in the view? {{item}} Basically I am using Ionic Framework trying to get the <ion-view view-title="{{var}}"> to update dynamically.
0

You can use Array.prototype.reduce, and write code in more functional way as below,

json.reduce(function(html, link){
    return html + (link['link-text'] ? link['link-text'] + ( json.indexOf(link) != json.length - 1 ?  ' / ' : '') : '');
}, '');

Demo : JSFiddle

Comments

0

You should declare data earlier to make it visible to all of the iterations of the json object, and then concatenate values to it rather than overwriting it every time.

 var data = '';
 for(var i = 0; i < json.length; i++) {
   data += json[i]['link-text'];
   if(i !== json.length - 1) data += ' / ';  
 }

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.