1

If I have the following object:

var record = {
    title: "Hello",
    children: [
        {
            title: "hello",
            active: true
        },
        {
            title: "bye",
            active: false
        }
};

I want to use underscore to determine if one of the children within the record has or does not have a title equal to a variable that will come from a form post, but also needs to be case insensitive... So for example:

var child = { title: "heLLo", active: true }

And underscore ( and this is wrong, and what I need help with ):

if ( _.contains(record.children, child.title) ) {
    // it already exists...
} else {
    // ok we can add this to the object
}

So basically I don't understand how to do this with underscore when dealing with array objects that have multiple key/value pairs. Also what is the best method for ignoring case? Should this be done in the underscore _.contains function? Regex? Use toLowerCase() beforehand to create the variables? If someone types in any variation of "Hello", "HELLO", "heLLO", etc. I don't want the insert to take place.

Thank you!

1 Answer 1

2

Use _.find and RegExp with "i" case-ignore flag

var valueFromPost = "bye";
var someOfChildrenHasValueFromPost = _.find(record.children,function(child){
    return child.title.match(new RegExp(valueFromPost,"i"));
});

Update

Here is an example @JSFiddle

JS code:

record = {
    children:[
        {title:'bye'},
        {title:'Bye'},
        {title:'Hello'}
        ]
}
var testValue = function(value) {
    return  _.find(record.children,function(child){
        return child.title.match(new RegExp(value,"i"));
    });
}
console.debug(testValue('Bye')); //returns object with "Bye" title
console.debug(testValue('What'));//returns undefined
console.debug(testValue('bye')); //returns object with "bye" title
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I'm having a problem though. This is returning a value each time no matter what I use as the form post. For example if I console.log(someOf....) I get Object {title: "test", sort: "", active: false} each time, so I'm unable to create an "undefined" scenario. What could I be doing wrong?

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.