javascript - js 中是否有类似 'lies in' 运算符的内容,因为我们在 mongoose/mongo 中有 '$in'

标签 javascript arrays

我想在js中实现这样的功能

            function(arrayOfObjects, arrayOfValues, property) {

/*here i want to return all the objects of 'arrayOfObjects' 
        which satisfies the following condition 
        (index is the iterative index of array 'arrayOfObjects')
               arrayOfObjects[index][property] is equivalent to any of
    the values that lies in arrayOfValues */

            };

示例:

arrayOfObjects = [{ a: 1, b: 2 }, { a: 3, b:4 }, { a: 1, b :3 }];
arrayOfValues = [ 2, 3 ];

function(arrayOfObjects, arrayOfValues, 'b')

应该返回 [{ a: 1, b: 2 }, { a: 1, b :3 }]

最佳答案

arrayOfObjects.filter(function (elem) {
    return elem.hasOwnProperty(property)
        && -1 !== arrayOfValues.indexOf(elem[property]);
});

如果您需要 IE8 支持:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#Compatibility

关于javascript - js 中是否有类似 'lies in' 运算符的内容,因为我们在 mongoose/mongo 中有 '$in',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20474243/

相关文章:

ios - 删除Char * Array Objective C中的第一个元素

javascript - 如何通过 Javascript 更改 css 类样式?

javascript - 在自定义过滤器中使用数组

javascript - JQuery 在加载时搞乱了页面

javascript - d3js 缩放事件处理程序未正确触发事件

php - 警告: count(): Parameter must be an array or an object that implements Countable in C:\xampp\htdocs\m2\my booking.php on line 158

c# - 从字节数组中获取字节 block 的起始位置

javascript - 两个不同的动态 promise 提供者链之间的等价

javascript - 将数组值赋给变量

用 c 中的数组构造我自己的 strcat 函数