从匹配数组的嵌套数组中获取名称
我有一些数组,如果它们包含相似的值,我想返回这些数组的名称。
I have some arrays, and if they contain similar values, I would like to return the name of those arrays.
var x = {
"food": ['bacon', 'cheese', 'bread', 'tomato'],
"utilities": ['plates', 'forks', 'spatulas'],
"guests": ['john', 'matt', 'bill']
},
y = ['bacon', 'tomato', 'forks'];
我的变量 x
,它有多个数组,名称为 food
,或 utilities
,或来宾
。所有 y
包含的,是某些值在 x
变量中的某些数组中是相同的。我需要返回包含 bacon
, tomato
和 forks 在他们的数组中。所以对于这个例子,我需要返回:
[food,utilities]
。
I have my variable x
, and it has multiple arrays, with a name either food
, or utilities
, or guests
. All that y
contains, is some values that are the same within some of those arrays in the variable of x
. I need to return the name of the arrays that contain bacon
,tomato
, and forks
in their arrays. So for this example, I need to return: ["food", "utilities"]
.
function getContainerName(obj, values) {
return Object.keys(obj).find(function(key) {
return values.every(value => obj[key].find(function(elem) {
return elem === value;
}));
});
}
console.log(getContainerName(x, y));
当通过此函数抛出它们时,我收到错误 ******* **
。我怎么去拿一个 [食物,实用程序]
的返回数组?
When throwing them through this function, I get an error *********
. How may I go and get a returned array of ["food", "utilities"]
?
Object.keys
上的简单 reduce()
将完成工作
var x = {
"food": ['bacon', 'cheese', 'bread', 'tomato'],
"utilities": ['plates', 'forks', 'spatulas'],
"guests": ['john', 'matt', 'bill']
},
y = ['bacon', 'tomato', 'forks'];
let res = Object.keys(x).reduce((a, b) => {
if (x[b].some(v => y.includes(v))) a.push(b);
return a;
}, []);
console.log(res);
对于你的评论 - 使用var和普通函数:
For your comment - with var and normal function:
var res = Object.keys(x).reduce(function (a, b) {
if (x[b].some(function (v) {
return y.indexOf(v) !== -1;
})) a.push(b);
return a;
}, []);