Search code examples
javascriptlinqlinq.js

How can get all objects whose sub object's property matches my string array using linq.js?


I have an array of tag names:

var tags = ['tagOne', 'tagTwo']

Which I want to use, to query the array below and get all items which match a tag.

var items = 
[
{
  'name': 'itemOne',
  'tags': [
    { name: 'tagOne' }
  ]
},
{
  'name': 'itemTwo',
  'tags': [
    { name: 'tagTwo' }
  ]
}
];

How can I do this with linq Js? I.E in this case both items would be returned


Solution

  • Try this; it may not be the most efficient way (I've never used linq.js before) but it will work:

    // Enumerate through the items
    var matches = Enumerable.From(items)
        .Where(function(item) {
            // Enumerate through the item's tags
            return Enumerable.From(item.tags).Any(function(tag) {
    
                // Find matching tags by name
                return Enumerable.From(tags).Contains(tag.name);
            })
        })
        .ToArray();