1

I have this field, and I am using underscore js

I'm trying to access the _id field if it contain .tgz

<html> 
    <head> 
        <title>_.contains() function</title> 
        <script type="text/javascript" src= 
        "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > 
        </script> 
        <script type="text/javascript" src= 
        "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js"> 
        </script> 
    </head>        
    <body> 
        <script type="text/javascript"> 
            var people = [ 
                {"id_": "sakshi.tgz"}, 
                {"id_": "aishwarya.zip"}, 
                {"id_": "ajay.tgz"}, 
                {"id_": "akansha.yml"}, 
                {"id_": "preeti.json"} 
            ] 
         console.log(_.where(people, {id_: "sakshi.tgz"})); 
        </script> 
    </body>  
</html> 

I only know how to do the exact match.

console.log(_.where(people, {id_: "sakshi.tgz"})); 

Expected Result

As you can see, I'm trying to get 2 of them that end with .tgz.

Any hints for me ?

Fiddle : https://codepen.io/sn4ke3ye/pen/KKzzzLj?editors=1002

2 Answers 2

1

If you have a string, and you want to know whether its last four characters are equal to '.tgz', this is one possible way to do it (MDN: slice):

aString.slice(-4) === '.tgz' // true or false

If that string is the id_ property of some object, just reference the id_ property first and then call slice on it:

someObject.id_.slice(-4) === '.tgz' // true or false

This is something we want to do with every object in a collection, so it is our iteratee. In order to have it applied repeatedly, we wrap it into a function:

function idEndsWithTgz(obj) {
    return obj.id_.slice(-4) === '.tgz';
}

Now we can use this iteratee with _.filter:

console.log(_.filter(people, idEndsWithTgz));

For a more thorough introduction to Underscore, you can also refer to another recent answer of mine: https://stackoverflow.com/a/63088916/1166087

Sign up to request clarification or add additional context in comments.

Comments

1
let newArr = people.filter(obj => obj._id.substr(obj._id.length -4) === ".tgz");

I use filter and substr JavaScript built-in methods of sorting the _id that ends with .tgz.

Comments

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.