使用Underscore.js提取包含特定字符串的特定对象

问题描述

我有此字段,正在使用下划线js

我尝试访问_id字段,如果其中包含.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> 

我只知道如何进行完全匹配匹配。

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

预期结果

如您所见,我正在尝试让其中2个以.tgz结尾。

有什么提示吗?

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

解决方法

如果您有一个字符串,并且想知道它的后四个字符是否等于'.tgz',那么这是一种可行的方式(MDN: slice):

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

如果该字符串是某个对象的id_属性,只需先引用id_属性,然后在其上调用slice

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

这是我们要处理集合中每个对象的事情,因此它是我们的iteratee。为了使其重复应用,我们将其包装到一个函数中:

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

现在我们可以将此迭代器与_.filter一起使用:

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

要获得有关Underscore的更全面介绍,您还可以参考我的另一个近期答案:https://stackoverflow.com/a/63088916/1166087

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

我使用filtersubstr JavaScript内置方法对以_id结尾的.tgz进行排序。