简体   繁体   English

使用字符串从关联数组获取值

[英]Get value from associative array with string

I have a json response I'm getting from a server with different response structures. 我有一个从具有不同响应结构的服务器获取的json响应。

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. 我想知道是否有一种方法可以通过可重用的方法从关联数组中获取“ data.link”,其中linkVariableName是关联数组的键。

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

Yes you can, as explained here: Accessing nested JavaScript objects with string key 是的,您可以按照下面的说明进行操作: 使用字符串键访问嵌套的JavaScript对象

However, IMO the function tries to do too much. 但是,IMO该功能尝试执行太多操作。 Why does it need to parse the JSON and extract the value? 为什么需要解析JSON并提取值? 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM