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();

});
1
  • 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. Commented Jul 26, 2015 at 2:52

1 Answer 1

1

This will add the img: property:

response['img'] = 'testpic.jpg';
Sign up to request clarification or add additional context in comments.

2 Comments

This is actually similar to the answer in the second article you linked to in the question.
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!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.