0

I have the file default.json:

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

My code:

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

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

//search array in IPs

How can I search values of array in IPs (ip1, ip2, ip3) and whenever it's true, call a function? Preferably using an underscore function.

5
  • 3
    Do you mean "ip1": "192.168.0.1" instead of "ip1: 192.168.0.1"? (note the quotes). Commented Apr 5, 2016 at 16:28
  • You should also use a comma , after each line of the JSON file. Commented Apr 5, 2016 at 16:32
  • default.json is invalid JSON. You're defining an object using {} but you're not using keys and values, unless you remove the quotation marks around the whole line and just place them on the ip addresses. Commented Apr 5, 2016 at 16:34
  • Thanks, I've already edited. Commented Apr 5, 2016 at 16:40
  • Your default.json is still invalid unless you remove the "IPs": part, or add surrounding {}. Commented Apr 5, 2016 at 16:42

2 Answers 2

1

Assuming you fix default.json to be like this:

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

You can then search for the IPs matching

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;
Sign up to request clarification or add additional context in comments.

Comments

0

I used this solution (with underscore):

File default.json

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

The code:

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
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.