-2

I have JSON object from server and requirement is to always display last item from the array items. how can i achieve that task using AngularJs or native JavaScript ?

Below case i have to display text Chief Administrative Officer.

main.js

  angular.forEach($scope.rcsaErhTreeData, function(val) {
      angular.forEach(val, function(val) {
          console.log('this is the array value', val[0].text);
      });
  });

json.js

[{
    "uid": null,
    "index": 0,
    "selected": null,
    "expanded": null,
    "id": 2701,
    "text": "BAC Enterprise Wide",
    "parentId": 0,
    "items": [{
        "uid": null,
        "index": 0,
        "selected": null,
        "expanded": null,
        "id": 4114,
        "text": "Chief Administrative Officer",
        "parentId": 2701,
        "items": []
    }]
}]
hussain
  • 6,587
  • 18
  • 79
  • 152

2 Answers2

-1

if you try the following code in your context you will get the result.

console.log(JSON.stringify(items[items.length - 1]));

The console will show you the stringified output...

Thanks, Paras

pparas
  • 549
  • 4
  • 13
-2

I am not a Angular.js programmer, but the concept would be to: 1. Either do it in a loop and overwrite the variable value with the next value, that way, the last one will persist. -- Not recommended due to performance issues, and using a loop when it can be done without a loop. Pseudo code:

var outVal='';
angular.forEach($scope.rcsaErhTreeData, function(val) {
      angular.forEach(val, function(val) {
          outVal = val[0].text);
      });
  });
console.log('this is the last item value', outVal);
  1. Another approach would be find the length of the val array, and go to its last index to fetch its value. I am not a pro in this language so cannot give an example code. Sorry about that.
RajN
  • 47
  • 7