1

I am quite new to using Node.js. I was looking for a good way to parse and query a JSON object. I have the following JSON object loaded in as a file.

[
{"Key":"Accept","Values":["Application/x-www-form-urlencoded","Application/Json","Application/Xml"]},
{"Key":"Accept-Charset","Values":["UTF-8", "ISO-8859-1"]},
{"Key":"Accept-Encoding","Values":["compress", "gzip"]},
{"Key":"Accept-Language","Values":[]},
{"Key":"Accept-Ranges","Values":[]},
{"Key":"Age","Values":[]},
{"Key":"Allow","Values":[]},
{"Key":"Authorization","Values":["Bearer"]},
{"Key":"Cache-Control","Values":[]},
{"Key":"Connection","Values":[]},
{"Key":"Content-Encoding","Values":[]},
{"Key":"Content-Language","Values":[]},
{"Key":"Content-Length","Values":[]},
{"Key":"Content-Location","Values":[]},
{"Key":"Content-MD5","Values":[]},
{"Key":"Content-Range","Values":[]},
{"Key":"Content-Type","Values":["Application/x-www-form-urlencoded","Application/Json","Application/Xml"]},
{"Key":"Date","Values":[]},
{"Key":"ETag","Values":[]},
{"Key":"Expect","Values":[]},
{"Key":"Expires","Values":[]},
{"Key":"From","Values":[]},
{"Key":"Host","Values":[]},
{"Key":"If-Match","Values":[]},
{"Key":"If-Modified-Since","Values":[]},
{"Key":"If-None-Match","Values":[]},
{"Key":"If-Range","Values":[]},
{"Key":"If-Unmodified-Since","Values":[]},
{"Key":"Last-Modified","Values":[]},
{"Key":"Max-Forwards","Values":[]},
{"Key":"Pragma","Values":[]},
{"Key":"Proxy-Authenticate","Values":[]},
{"Key":"Proxy-Authorization","Values":[]},
{"Key":"Range","Values":[]},
{"Key":"Referer","Values":[]},
{"Key":"TE","Values":[]},
{"Key":"Trailer","Values":[]},
{"Key":"Transfer-Encoding","Values":[]},
{"Key":"Upgrade","Values":[]},
{"Key":"User-Agent","Values":[]},
{"Key":"Via","Values":[]},
{"Key":"Warning","Values":[]}
]

I want to be able to find a Key by value and return the values array.

So for example how do I find the values where the key is equal to Content-Type.

Thanks in advance for your help

4

2 回答 2

7

由于您使用的是 Node.js,因此您可以利用较新的Array.prototype.filter

var myData = require('./data.json'),
  myFilteredData = myData.filter(function(obj) {
    return obj.key === 'Content-Type';
  });
于 2013-09-02T16:53:09.913 回答
2

尽管有我的评论,我还是会像这样循环遍历数组:

function searchByKey(key) {
  for (var i = 0, l = arr.length; i < l; i++){
    if (arr[i]['Key'] === key) {
      return arr[i]['Values'];
    }
  }
  return false;
}
于 2013-09-02T16:49:32.837 回答