gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 15:51:23 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com