从匹配数组的嵌套数组中获取名称

阿卡多斯

我有一些数组,如果它们包含相似的值,我想返回这些数组的名称。


    var x = { 
      “ food”:['bacon','cheese','bread','tomato'],
      “ utilities”:['plates,'forks','spatulas'],
      “ guests”:[' john','matt','bill'] 
    },
    y = ['bacon','tomato','forks'];

我有我的变量x,它有多个数组,名称为food,或utilitiesguestsy包含的全部是与变量中的某些数组中的某些值相同的值x我需要返回包含数组的名称bacontomato以及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"]

ao

简单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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章