Mr. Trvp
Mr. Trvp

Reputation: 17

Get value from associative array with string

I have a json response I'm getting from a server with different response structures.

One uses another value "data" to store a link:

and the other doesn't (with "image" being the link):

I was wondering if there was a way I can get the "data.link" from the associative array with a reusable method, with linkVariableName being the key of the associative array.

function addLink(responseText, successVariableName, isError, linkVariableName)
{
    var jsonResponse = JSON.parse(responseText);

    var state;
    if (isError)
        state = !jsonResponse[successVariableName];
    else
        state = jsonResponse[successVariableName];

    if (state) {
        var link = jsonResponse[linkVariableName];
        insertAtCursor(textArea, '[img]' + link + '[/img]\r\n');
    } else
        console.log('Error: ' + responseText);
}

so I can use either

addLink(response.responseText, 'success', false, 'data.link');

or

addLink(response.responseText, 'error', true, 'image');

Upvotes: 0

Views: 127

Answers (1)

Felix Kling
Felix Kling

Reputation: 816404

Yes you can, as explained here: Accessing nested JavaScript objects with string key

However, IMO the function tries to do too much. Why does it need to parse the JSON and extract the value? You could just pass the value directly to it:

function addLink(link) {
  insertAtCursor(textArea, '[img]' + link + '[/img]\r\n');
}

And move the other logic to where you handle the response:

var isError = ...;
var response = JSON.parse(responseText);

if (isError && !response.error) {
  addLink(response.image);
} else if(!isError && response.success) {
  addLink(response.data.link);
} else {
  console.log('Error: ' + responseText);
}

Upvotes: 1

Related Questions