JavaScript - Looping and Adding Key Value Pair to JSON Object
I am trying to sort the "response", a JSON object passed through a function from the API, and insert the "img:" key and the src value of the image based on the planet name.
What I tried: I tried using response.push as shown in several StackOverflow links, but this just adds the key value to the entire object as a separate value. I also tried [i ]'s answer, but it doesn't look like my console is giving me an error.
Several links that I have visited . They are useful, but don't seem to refer to the loop sequence I will be after.
- Adding key value pair to json object
- How do I add a key / value pair to a JavaScript object?
- JS JSON Pair Key and Value
Any help or guidance would be appreciated.
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();
});
+3
source to share
1 answer