Javascript检查特定键值并从JSON打印另一个键值

时间:2016-11-14 09:28:17

标签: javascript html json

请不要JQuery。只有普通的Javascript。 我有一个特殊的JSON:data.json - >

{
        "items": [
            {
            "name": "primAppName",
            "title": "sample 1",
            "author": "author 1"},
            {
              "name": "primAppName",
            "title": "sample 2",
            "author": "author 2"},
            {
              "name": "primAppName",
            "title": "sample 3",
            "author": "author 3"},
            {
              "name": "secAppName",
            "title": "sample 4",
            "author": "author 4"},
            {
              "name": "secAppName",
            "title": "sample 5",
            "author": "author 5"}
        ]
}

在Javascript中,我想要做的是,如果JSON密钥 - “名称”具有子字符串“ primApp ”的值,那么我想追加“作者“价值” witDetails “span,如果值有子串” secApp “,那么我想追加”作者 “值为” eanDetails “span。

这是一个包含完整代码的plunker。 (我的代码包含几个文件。这就是添加到plunkr的原因。)

所需输出:This is an pictoral view of what I am trying to achieve.

loadFunctionJSON = function() {

  //
  //	var data = JSON.parse(data);
  var div = document.getElementsByClassName('functionJSONList')[0];
  var witSpan = document.getElementById("WITDetails");
  var eanSpan = document.getElementById("EANDetails");
  $http('data.json').get().then(function(res) {
    if (res) {
      var data = res.items;
      for (var event in data) {
        var dataCopy = data[event];
        for (var key in dataCopy) {
          if (key.match(/name|value/)) {

            if (key == "name" && dataCopy[key].indexOf("secApp") !== -1) {
              var para = document.createElement("P"); // Create a <p> element
              var t = document.createTextNode(dataCopy[key]); // Create a text node
              para.appendChild(t); // Append the text to <p>
              witSpan.appendChild(para); // Append <p> to <body>
            }
            //      console.log('key : ' + key + ':: value : ' + dataCopy[key]);
          }
        }
      }
    }
  });
};

/********* --AJAX Service-- ****************/
function $http(url) {
  // A small example of object
  var core = {
    // Method that performs the ajax request
    ajax: function(method, url, args) {
      // Creating a promise
      var promise = new Promise(function(resolve, reject) {
        // Instantiates the XMLHttpRequest
        var client = new XMLHttpRequest();
        var uri = url;
        if (args && (method === 'PUT')) {
          uri += '?';
          var argcount = 0;
          for (var key in args) {
            if (args.hasOwnProperty(key)) {
              if (argcount++) {
                uri += '&';
              }
              uri += encodeURIComponent(key) + '=' + encodeURIComponent(args[key]);
            }
          }
        }
        client.open(method, uri);
        if (args && args.headers) {
          var keys = Object.keys(args.headers);
          for (var i = 0; i < keys.length; i++) {
            client.setRequestHeader(keys[i], args.headers[keys[i]]);
          }
        }
        if (args && args.data) {
          client.send(JSON.stringify(args.data));
        } else {
          client.send();
        }
        client.onload = function() {
          if (this.status >= 200 && this.status < 300) {
            // Performs the function "resolve" when this.status is equal to 2xx
            this.response ? resolve(JSON.parse(this.response)) : resolve(this);
          } else {
            // Performs the function "reject" when this.status is different than 2xx
            var data = {};
            try {
              data = JSON.parse(this.responseText);
            } catch (e) {
              data = this.statusText;
            }
            if (data.error && data.error.message && data.error.message == "Invalid bearer token") {
              BotUI.sessionOutOverlay();
            } else {
              reject(data);
            }
          }
        };
        client.onerror = function() {
          reject(this.statusText);
        };
      });
      // Return the promise
      return promise;
    },
    put: function(method, url, args) {
      var promise = new Promise(function(resolve, reject) {
        var request = new XMLHttpRequest();
        request.open(args.method, url, true);
        if (args && args.headers) {
          var keys = Object.keys(args.headers);
          for (var i = 0; i < keys.length; i++) {
            request.setRequestHeader(keys[i], args.headers[keys[i]]);
          }
        }
        request.onreadystatechange = function() {
          if (request.status && request.readyState != 2) {
            if (request.readyState == 4 && request.status == 201) {
              return resolve({
                headers: request.getAllResponseHeaders(),
                data: JSON.parse(request.responseText)
              });
            } else if (200 == request.status && request.readyState == 4) {
              if (!!request.responseText) {
                if ((request.responseText).charAt(0) !== '<') {
                  resolve({
                    data: {
                      status: request.status,
                      response: JSON.parse(request.responseText)
                    }
                  });
                } else {
                  return reject(request.responseText);
                }
              } else {
                resolve({
                  data: {
                    status: request.status
                  }
                });
              }
            } else {
              if (request.readyState == 4 && request.status != 201) return reject(request.responseText);
            }
          }
        };
        if (args.isImage) {
          request.send(args.data);
        } else {
          request.send(JSON.stringify(args.data));
        }
      });
      return promise;
    }
  };
  // Adapter pattern
  return {
    'get': function(args) {
      return core.ajax('GET', url, args);
    },
    'post': function(args) {
      return core.ajax('POST', url, args);
    },
    'put': function(args) {
      return core.put('PUT', url, args);
    },
    'delete': function(args) {
      return core.ajax('DELETE', url, args);
    }
  };
}
/* Styles go here */

.functionRightCol {
  float: right;
  width: 50%;
}
.functionLeftCol {
  float: left;
  width: 50%;
}
.WITEntityName {
  text-transform: uppercase;
  text-align: center;
}
.BOTPropertyName {
  text-transform: uppercase;
  text-align: center;
}
<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="style.css">
  <script src="script.js"></script>
  <script type="text/javascript" src="data.json"></script>
  <script src="api.js"></script>
</head>

<body onload="loadFunctionJSON()">
  <div class="functionJSONList">
    <div name="functionWIT" id="functionWIT" class="functionWIT"></div>
    <span id="WITDetails" style='text-align:left'>WIT</span>
    <div name="functionEAN" id="functionEAN" class="functionEAN"></div>
    <span id="EANDetails" style='text-align:left'>ENTITY APP NAME</span>
    <div class="functionResults">
      <span class="WITEntityName functionLeftCol">WIT Entity Name</span>
      <span class="BOTPropertyName functionRightCol">BOT Property Name</span>
    </div>
  </div>
</body>

</html>

1 个答案:

答案 0 :(得分:1)

你可以使用forEach在json中循环。

希望这会有所帮助。

var data = {
        "items": [
            {
            "name": "primAppName",
            "title": "sample 1",
            "author": "author 1"},
            {
              "name": "primAppName",
            "title": "sample 2",
            "author": "author 2"},
            {
              "name": "primAppName",
            "title": "sample 3",
            "author": "author 3"},
            {
              "name": "secAppName",
            "title": "sample 4",
            "author": "author 4"},
            {
              "name": "secAppName",
            "title": "sample 5",
            "author": "author 5"}
        ]
};

var a = document.getElementById('a');
var b = document.getElementById('b');

data.items.forEach(function(item){
   if(item.name.indexOf("primApp") >=0 ){
     a.innerHTML = a.innerHTML + item.author +" ";
   }else if(item.name.indexOf("secApp") >=0 ){
     b.innerHTML = b.innerHTML + item.author +" ";
   }
});
<span id="a"></span>
<br/><br/>
<span id="b"></span>