Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Looping and adding a key value pair to JSON object

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.

  • Appending a key value pair to a json object
  • How can I add a key/value pair to a JavaScript object?
  • JS JSON Pair Key & Value

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

});
like image 604
Matt G. Avatar asked Dec 06 '25 07:12

Matt G.


1 Answers

This will add the img: property:

response['img'] = 'testpic.jpg';
like image 64
DarthDerrr Avatar answered Dec 07 '25 19:12

DarthDerrr