0

I have declared it as below and also showing data is actually coming from the server but the following code doesn't work if there are multiple arrays in the data coming from the server.

$scope.items = [ { id: “”, locations: [{ name: “” }] } ] Data from server looks this way. $scope.data = [ { id: '1', type: 'a1', year: '1999', locations: [ {id:'1', name: 'abc'}, {id:'11', name: 'xyz'}] }, { id: '11', type: 'a2', year: '2000', locations: [ {id:'22', name: 'abc1'}, {id:'23', name: 'xyz1'}, {id:'24', name: 'efg1'}] } ... ]

 for (var i=0; i<$scope.data.length; i++) { $scope.items[i].id = $scope.data[i].id; for(var j=0; j<$scope.data[i].locations.length; j++) { $scope.items[i].locations[j].name = $scope.data[i].locations[j].name; } }

    1 Answer 1

    1

    I have done something like this earlier.

    I created a function which would return a json object which in your case would be like

    $scope.getJson = function(){ return { id: “”, locations: [] } } 

    Now you have to modify your loop a little bit to handle multiple JSONArray elements like

     for (var i=0; i<$scope.data.length; i++){ var temp = $scope.getJson(); temp.id = $scope.data[i].id; temp.locations = $scope.data[i].locations; $scope.items.push(temp); }

    If you want to copy some specific properties from $scope.data[i].locations only, then you can use another loop else you can assign the locations array directly.

    5
    • Hi Amit! I have added the sample output array as how it looks like. So locations is dynamic as well. And there can be multiple items in the data array
      – sai123
      CommentedMar 13, 2018 at 4:50
    • Btw, why don't you simply try assigning server data as $scope.items = $scope.data;CommentedMar 13, 2018 at 4:54
    • I actually have additional fields in server data which I don't need. Please check the updated server data. I tried your solution but doesn't work for me.
      – sai123
      CommentedMar 13, 2018 at 5:01
    • Try the above solution, it should work for different sized locations array too!CommentedMar 13, 2018 at 6:41
    • Thanks! Works great
      – sai123
      CommentedMar 13, 2018 at 17:42

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.