Matt G.
Matt G.

Reputation: 105

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.

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

});

Upvotes: 3

Views: 2570

Answers (1)

DarthDerrr
DarthDerrr

Reputation: 491

This will add the img: property:

response['img'] = 'testpic.jpg';

Upvotes: 1

Related Questions