我正在为 Mixitup 构建一个过滤方法并且我需要能够针对 x 个选定参数进行正确过滤。 (这里的插件并不重要,重要的是我如何获得正确的最终对象)
我目前有一个对象,它为每个唯一搜索发送一个唯一键及其匹配对象(通过 filter 方法获得)到我的过滤函数中。
这是我迷路的地方。
我需要能够遍历我的对象,它是关联的键=>值(对象),并且只取出每个对象中存在的对象。
例如,(我有 jQuery 对象而不是数字)
var filter = {
x : {1,3,5,6},
y : {1,4,7,8},
z : {1,9}
}
根据上面的例子,唯一返回的对象是 - 1(因为它是唯一一个存在于所有三个键中的对象。
如有任何帮助,我们将不胜感激!
最佳答案
使用 Array.reduce
和 Array.filter
的简短方法:
基本上它从第一个数组开始作为 reduce 的起始值。然后通过查找索引来过滤结果集,如果找到,则保留该值,否则跳过该值。这一直持续到对象没有更多属性为止。
var filter = {
x: [1, 3, 5, 6],
y: [1, 4, 7, 8],
z: [1, 9]
};
var filtered = Object.keys(filter).reduce(function (r, a, i) {
return i ? r.filter(function (b) {
return ~filter[a].indexOf(b);
}) : filter[a];
}, []);
document.write('<pre>' + JSON.stringify(filtered, 0, 4) + '</pre>');
对象的奖励,返回公共(public)键:
var filter = {
x: { a: 'ah', c: 'ce', e: 'eh', f: 'ef' },
y: { a: 'ah', d: 'de', g: 'ge', h: 'ha' },
z: { a: 'ah', i: 'ie' }
};
var filtered = Object.keys(filter).reduce(function (r, a, i) {
return i ? r.filter(function (b) {
return b in filter[a];
}) : Object.keys(filter[a]);
}, []);
document.write('<pre>' + JSON.stringify(filtered, 0, 4) + '</pre>');
关于javascript - 比较对象并仅获取所有对象中存在的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31965863/