我想在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/