簡體   English   中英

如何迭代以數組為值的對象

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

例如 :

我有一個對象,在那個對象中,我在數組中有值。 我想返回包含鍵的數組,該鍵包含作為變量傳遞的值。

 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);
}```

有多種方法可以解決這個問題。
一種可能是使用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);    
};

這也可以用reduce()來完成,但我發現用這種方式解釋起來更容易。

另一種方法是使用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