Reputation: 14226
So I have an object array that I need to check against a few variables I'm being sent. I am using underscore (plain javascript is fine too though) I have the object array looking like so -
var o = [{
module: "mod1",
customUrl: [{
"state": "name1",
"options": ["option1", "option2", "option3"]
}, {
"state": "name2",
"options": ["option1", "option2", "option3"]
}]
}, {
module: "mod2",
customUrl: [{
"state": "name1",
"options": ["option1", "option2", "option3"]
}, {
"state": "name2",
"options": ["option1", "option2", "option3"]
}]
}]
I have a function where I'm being passed three vars I would like to check if the last one exists inside of the first 2. Let me show you what I mean
test = function (module, state, option){
}
So what I am looking to do is, for example if I passed in
test(mod1,name1, option2);
I would like to check if there is a module with a key of "mod1", and then inside of that object there is an object inside of custom url with a state of "name1", and if that objects options array has the value "options2" inside of it. This is some more serious traversal, I could use some help. Thanks for reading!
Upvotes: 1
Views: 480
Reputation: 42530
A plain JavaScript version:
function test(o, module, state, option) {
return o.some(function(o) {
return o.module == module && o.customUrl.some(function(o) {
return o.state == state && o.options.indexOf(option) != -1;
})
});
}
Upvotes: 2
Reputation: 255155
With Underscore.js it will be as simple as
function testContains(o, module, state, option) {
return _.chain(o)
.findWhere({module: module})
.result('customUrl')
.findWhere({state: state})
.result('options')
.contains(option)
.value();
}
Demo: http://jsfiddle.net/3f1n32tj/
Upvotes: 4
Reputation: 13497
Here's an example of how you could do this with lodash. (Note that I named your o
array objects
because o
seemed confusing in the example.):
function test(moduleName, stateName, optionName) {
var object = _.find(objects, function(object) { return object.module == moduleName; });
if (object) {
var customUrl = _.find(object.customUrl, function(customUrl) { return customUrl.state == stateName; });
if (customUrl) {
var option = _.find(customUrl.options, function(option) { return option == optionName; });
}
}
return !!option;
}
See http://jsfiddle.net/bvaughn/53h6zoeq/
You could obviously implement the same thing with vanilla JS.
Upvotes: 1
Reputation: 114599
You can just traverse the data structure using two loops:
o.forEach(function(m) {
if (m.module === mod1) {
m.customUrl.forEach(function(s) {
if (f.state === name1 &&
f.options.indeOf(option2) >= 0) {
// We found it (one of them)
}
});
}
});
The third loop can be avoided using indexOf
on the array.
Upvotes: 0