使用下划线在数组中搜索JSON值

时间:2016-04-05 16:26:34

标签: javascript node.js underscore.js

我有文件default.json

{
    "IPs": {
        "ip1": "192.168.0.1",
        "ip2": "192.168.0.2",
        "ip3": "192.168.0.3"
    }
}

我的代码:

var _      = require('underscore'),
    config = require('default.json')

var array  = ['192.168.0.1', '192.168.0.2']

//search array in IPs

如何在arrayIPsip1ip2)中搜索ip3的值,只要它为真,请拨打功能?最好使用下划线功能。

2 个答案:

答案 0 :(得分:1)

假设您将default.json修改为:

"IPs": {
    ip1: "192.168.0.1",
    ip2: "192.168.0.2",
    ip3: "192.168.0.3"
}

然后,您可以搜索匹配的

var foundIPs = Object.keys(config.IPs).filter(function(name) {
  // name will be something like 'ip1', 'ip2', or 'ip3'
  var currIP = config.IPs[name]; // eg. currIP = "192.168.0.1"
  var inArray = array.indexOf(currIP) > -1;
  return inArray;
});
var foundIP = foundIPs.length > 0;

答案 1 :(得分:0)

我使用此解决方案(使用underscore):

档案default.json

    {
        "IPs": {
            "ip1": "192.168.0.1",
            "ip2": "192.168.0.2",
            "ip3": "192.168.0.3"
        }
    }

代码:

var _      = require('underscore'),
    config = require('default.json')

var array = ['192.168.0.1', '192.168.0.2']
var IPs   = config.IPs

_.each(IPs, function(e, k){
    //if find IPs in array
    if(array.indexOf(e) > -1)
        //do something
    else
        //do something
})