0

I have an array of objects which I loop over and run a getJSON if the object.name property matches a string. I am using $.then to handle the response. I would like to know how I can pass an extra argument to the response function called in $.then?

//Current code

var letters = [
    {name:"a", tag1:103, tag2:102},
    {name:"b", tag1:3},
    {name:"c", tag1:10},
    {name:"d", tag1:11, tag2:14},
    {name:"e", tag1:79, tag2:80},
    {name:"f", tag1:23, tag2:17},
];

function handleResponse(responseText) {
    console.log(responseText);
}

for (var i=0; i<letters.length; i++) {
    if (letters[i].name === "e") {
        $.getJSON(url).then(handleResponse);
    }
}

//What i need

function handleResponse(responseText, name) {
    console.log(name);
    console.log(responseText);
}

for (var i=0; i<letters.length; i++) {
    if (letters[i].name === "e") {
        $.getJSON(url).then(handleResponse(data, letters[i].name);
    }
}
Sai
  • 801
  • 3
  • 10
  • 27
  • `letters[i].name` is always going to be `e` in `handleResponse`. What do you actually need this for? – Luca Kiebel Apr 24 '18 at 10:21
  • @luca Thanks for the response, I just need to know how I can pass an extra argument to the function if it's possible – Sai Apr 24 '18 at 10:24
  • You can use [bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind). – t.niese Apr 24 '18 at 10:25
  • @t.niese I looked at that before but didn't notice the switch between the parameters and arguments. Could you explain why the first parameter is the second argument? – Sai Apr 24 '18 at 10:31

0 Answers0