简体   繁体   English

如何迭代以数组为值的对象

[英]How to iterate over an object which have array as value

For Example :例如 :

I have an object and in that object, I have values in the array.我有一个对象,在那个对象中,我在数组中有值。 I want to return the array which contains the key which contains the value passing as a variable.我想返回包含键的数组,该键包含作为变量传递的值。

 function getValues(val , object){
  return []; // return [b,c] because xyz are present in both
}

var object = {
     "a" : ["abc", "cde","efg"],
     "b" : ["asdf","asee","xyz"],
     "c" : ["asaw","wewe","xyz"]

  getValues("xyz", object);
}```

There are various ways to approach this.有多种方法可以解决这个问题。
One could be using Object 's native functions:一种可能是使用Object的本机功能:

function getValues(str, obj) {
  return Object
     // returns the entries pairs in a array of [key, value]
    .entries(obj)
    // from the array it searches the value for the string inputted and maps it back
    .map(([key, array]) => array.includes(str) ? key : undefined)
    // simply remove the undefined returned values from map()
    .filter((value) => value);    
};

This could have been done with reduce() as well but I found it easier to explain this way.这也可以用reduce()来完成,但我发现用这种方式解释起来更容易。

Another approach is using a for loop to iterate over the keys of the object:另一种方法是使用for循环遍历对象的键:

function getValues(str, obj) {
  let arr = [];
  // Iterates through the object selecting its keys
  for (let key in obj) {
    // If the array of the current key has the string in it, includes in the array
    if (obj[key].includes(str)) {
      arr.push(key)
    }
  }
  return arr;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM