How can I use sugar.js to search arrays in objects?

1.1k Views Asked by At

I have an array of objects. Each object is a municipality, with it's name, an alternate spelling, and an identifying number.

var munis = [
    {
        name: 'St. Louis Hills',
        alt: 'Saint Louis Hills',
        nhdNum: 992
    },
    {
        name: 'Mount Pleasant',
        alt: 'Mt. Pleasant',
        nhdNum: 1004
    }
];

In my application, users can type a name. Then I use Sugar.js to search this array and return the particular object which matches what they typed, like this:

var theMatch = munis.find(function(el) { 
    return el.name === userInput || el.alt === userInput; 
});

This works well, but only allows me to use one canonical name and one alternate spelling. I'd like to have multiple alternates, like this:

{
    name: 'Mount Pleasant',
    alt: ['Mt. Pleasant','Mt Pleasant'],
    nhdNum: 1004
}

But I can't figure out how to adapt Sugar's .find() to search this structure. Can anyone help?

2

There are 2 best solutions below

0
Ven On BEST ANSWER

Just use Array::indexOf :

var theMatch = munis.find(function(el) { 
   return el.name === userInput ||
     el.alt.indexOf(userInput) > -1;
});
0
Govan On

You can use nested find function:

var theMatch = munis.find(function(el) { 
    return el.name === userInput || el.alt.find(userInput); 
});

If you use indexOf it will return the index only but this will return the object containing the value.