我有一些数组,如果它们包含相似的值,我想返回这些数组的名称。
var x = { “ food”:['bacon','cheese','bread','tomato'], “ utilities”:['plates,'forks','spatulas'], “ guests”:[' john','matt','bill'] }, y = ['bacon','tomato','forks'];
我有我的变量x
,它有多个数组,名称为food
,或utilities
或guests
。所y
包含的全部是与变量中的某些数组中的某些值相同的值x
。我需要返回包含数组的名称bacon
,tomato
以及forks
在他们的阵列。因此,对于此示例,我需要返回:["food", "utilities"]
。
函数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));
通过此函数抛出它们时,出现错误*********
。我怎样才能得到返回的数组["food", "utilities"]
?
简单reduce()
就Object.keys
可以完成工作
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和正常功能:
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;
}, []);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句