Search code examples
javascriptangularjsloopbackjs

Look if loopback model property array contains a string


I have a Loopback moddel that looks like this:

{
 "name": "string",
 "elements": [
      "string"
  ]
}

Now I want to filter if elements property conatins a certain string. Something like this:

User.find({
     filter: {
         where: {elements: $scope.objects[i].id} //doesn't work, I want sth like "element contains $scope.objects[i].id
     }}, function (user) {
        console.log(user);
});

Solution

  • Warning: This solution was meant to answer the question "how do I filter a list of objects". It was accepted so I can't remove it. I don't know anything about LoopBack which has performance implications I'm not privy to. So please keep searching if you are looking for a "LoopBack" best practice.


    This seems like a javascript question to me. The elements property contains an array so you can filter that array with filter().

    yourModel = {      // <-- Using a plain object for demo.
     "name": "string",
     "elements": [
          "string"
      ]
    }
    
    matchingElements = yourModel.elements.filter(function(elm){ return elm === $scope.objects[i].id});
    
    didMyModelHaveTheElement = matchingElments.length > 0;