3

I'm attempting to sort through 'response', a JSON object passed through the function from an API, and insert a key 'img:' and a value, the image src, based on the planet's name.

What I have tried: I tried using response.push as found in a few StackOverflow links, but that just adds the key value to the entire object as a separate value. I also tried response[i], but that doesn't seem to be valid since my console gives me an error.

A Few of the Links I've Visited These are helpful, but don't seem to address the looping sequence I'm after.

I would appreciate any help or guidance.

  app.controller('mainCtrl', function($scope, parseService) {

  $scope.getParseData = function() {
    parseService.getPlanet().then(function(response) {

      for(var i = 0; i < response.length; i++)
        if (response[i].name === "Hoth") {
          console.log("We found hoth!");
          response.push({'img': 'testpic.jpg'}); //Trouble w. this line
        } else {
          console.log("not Hoth");
        }
        $scope.planets = response;

    });
  }
  $scope.getParseData();

});
Community
  • 1
  • 1
Matt G.
  • 105
  • 2
  • 12
  • Can you change `console.log('We found hoth!')` to `console.log(response)` and post the results? It'd be helpful to know what that object is. My guess is that it isn't an array, so you need to do something different. – Chris Anderson Jul 26 '15 at 02:52

1 Answers1

1

This will add the img: property:

response['img'] = 'testpic.jpg';
DarthDerrr
  • 461
  • 3
  • 9
  • This is actually similar to the answer in the second article you linked to in the question. – DarthDerrr Jul 26 '15 at 02:56
  • Thanks for the nudge in the right direction. I had to do `response[i]['img'] = 'testpic.jpg'; ` and this worked perfectly. I don't know why I didn't see that as an option. I'm still pretty new to this stuff. Thank you for your help! – Matt G. Jul 26 '15 at 03:27