使用没有嵌套循环js的数组过滤对象数组 [英] filtering an array of objects using an array without nested loops js
问题描述
我一直试图找出最干净的方法来过滤对象数组而不使用嵌套循环.
我发现使用.filter
函数有关使用另一个数组过滤数组的帖子未能弄清楚如何使用相同的模式实际访问对象数组中的对象内的右键
给定下一个对象数组:
I have been trying to figure out the cleanest way to filter an array of objects without using nested loops.
I found this post using .filter
function about filtering an array using another array but I failed on figuring out how to actually access the right key within the object in array of objects using the same pattern
Given the next following array of objects:
[ { technology: 'CHARACTER', score: -1 },
{ technology: 'PRESSURE_RELIEF', score: 2 },
{ technology: 'SUPPORT', score: 3 },
{ technology: 'MOTION_ISOLATION', score: 2 },
{ technology: 'TEMPERATURE_MANAGEMENT', score: -1 },
{ technology: 'COMFORT', score: 2 } ]
我想使用以下数组过滤不需要的数组:
I want to use the following array to filter the ones I don't need:
[CHARACTER, MOTION_ISOLATION, TEMPERATURE_MANAGEMENT]
是否可以在不使用嵌套循环的情况下访问它?如果可能的话,我也愿意提出建议.
Is it even possible to access it without using a nested loop? I'm also open to suggestions if not possible.
推荐答案
您可以使用 .indexOf
像这样
You can use .filter
with .indexOf
like so
var condition = ['CHARACTER', 'MOTION_ISOLATION', 'TEMPERATURE_MANAGEMENT'];
var data = [
{ technology: 'CHARACTER', score: -1 },
{ technology: 'PRESSURE_RELIEF', score: 2 },
{ technology: 'SUPPORT', score: 3 },
{ technology: 'MOTION_ISOLATION', score: 2 },
{ technology: 'TEMPERATURE_MANAGEMENT', score: -1 },
{ technology: 'COMFORT', score: 2 }
];
var result = data.filter(function (el) {
return condition.indexOf(el.technology) < 0;
});
console.log(result);
这篇关于使用没有嵌套循环js的数组过滤对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!