使用AJAX获取对象并将JSON字符串数据与当前值进行比较

3

我的函数将从外部api接收一个数组对象,我可以将其转换为JSON格式。假设这是我的JSON对象的样子:

{
        "id": 99,
        "title": null,
        "author": "user",
        "content": "content",
        "url": "https://stackoverflow.comt"
    },

    {
        "id": 100,
        "title": null,
        "author": "user",
        "content": "content",
        "url": "https://www.google.com"
    }

从上面接收到的数据中分离出特定的键值对后,它的样子是这样的:
{"url":"https://www.google.com/"}

这个过程是异步调用的,当我点击扩展时触发,我可以在控制台中看到。现在在我的模板popup.html中。
    <td>
                <input type="text" name="url" id="url">
                <input type="hidden" name="content" id="content" value="content" />
            </td>

popup.js

chrome.tabs.query({active: true, currentWindow: true },
function callback(tabs) {
  var currentTab = tabs[0]; // there will be only one in this array
  $("#url").val(currentTab.url);
});

它从标签中获取当前URL并将其发送到post.js,其中进行后端操作。 现在我想检查URL数据并将其与JSON对象中的每个URL进行比较

我是Jquery / Javascript的新手。我尝试将此值与JSON中的每个值进行比较,但没有用。

2个回答

0

当您拥有键值对的json值时,请使用以下代码获取URL。

jsonKeyValuePair // assuming this variable has key value pair, having url.

var jsonData = JSON.parse(jsonKeyValuePair)
console.log(jsonData.url) // this should give you the url value 

// You can now compare

if(jsonData.url === currentTab.url) {
  // Do your calculation.
}

希望这能帮到你。


0

你可以使用过滤器(Filter)来匹配JSON对象中的URL,这是最简单和最清晰的比较方式。

let currentTab = tabs[0]; // Url for comparing

//jsonObj contains all the json urls
let matchedUrl= jsonObj.filter(function(item) {
  return item.url === currentTab.url;
});

console.log(matchedUrl);

当它到达“filter”时,我不会将其称为“Obj”,因为它是一个数组。 - Toni Leigh
只要它能完成工作,你可以随便给它起任何名字,我的朋友。 - Mr Khan
1
确实,语言环境可能会让你这么做,但好的程序员也会尽量使他们的代码易于理解。如果你随便给变量命名,那么其他开发人员(包括你自己在一个月或两个月后)将会很难处理。这可能会完成当时的工作,但当你需要回来修复漏洞时,这并不会有所帮助。 - Toni Leigh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接