简体   繁体   English

JavaScript比较两个json文件?

[英]JavaScript compare two json files?

I have 2 json files with data, one shows an article with data parameters and the other one shows a list of categories with it's own data parameters. 我有2个带有数据的json文件,一个显示带有数据参数的文章,另一个显示带有其自己的数据参数的类别列表。

The article json file has an attribute ID which is the ID of one of the categories in the Category json file. article json文件的属性ID是Category json文件中类别之一的ID。

When I load the page, I need to be able to tell if the article ID is the same is a Category ID. 加载页面时,我需要能够确定文章ID是否相同是类别ID。 If so, I want the data of the Category to populate some data in the page. 如果是这样,我希望类别的数据填充页面中的一些数据。

Right now all i've done is to create two ajax requests separately for each json file but I don't know how to make the comparison process... 现在我所要做的就是为每个json文件分别创建两个ajax请求,但是我不知道如何进行比较。

You can just turn the JSON result into a JavaScript Object via JSON.parse. 您可以通过JSON.parse将JSON结果转换为JavaScript对象。 Then iterate over the categories and find the one you are looking for. 然后遍历类别并找到您要寻找的类别。

Simplified Example: 简化示例:

<div id="output"></div>

(function() {
  var JSON_Categories = '[{ "id" : "1", "text" : "Category A"}, { "id" : 2, "text" : "Category B"}]';
  var JSON_Article = '{"id" : "1", "text" : "Article Text"}';

  var categories = JSON.parse(JSON_Categories);
  var article = JSON.parse(JSON_Article);

  var outputElement = document.getElementById('output');

  categories.forEach(function (category) {
      if (category.id === article.id) {
        outputElement.textContent = category.text;
        outputElement.textContent += ': ' + article.text;
      }
  });

})();

http://codepen.io/jjd/pen/WrQNwJ?editors=101 http://codepen.io/jjd/pen/WrQNwJ?editors=101

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

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