如何找到包含值的对象键's数组

How to find an object key that contains a value within it's array?

本文关键字:数组 对象 何找 包含值      更新时间:2023-09-26

我有以下Javascript(Coffeescript)对象:

urlSets =
  a: [
    'url-a.com'
    'url-b.com'
    'url-c.com'
    ]
  b: [
    'url-d.com'
    'url-e.com' 
    'url-f.com'
    ]
  c: [
    'url-g.com'
  ]

如果我有值"url-a.com",我如何找到包含此url的urlSetskey

我已经在使用underscore.js库,并认为我可能会使用_.findKey_.contains。我一直在玩这样的东西:

_.findKey urlSets, (key) ->
  return _.contains(key, "url-a.com")

……但运气不好。返回TypeError: undefined is not a function

我发现不使用任何特殊的库进行这种循环更容易,尤其是当使用具有如此漂亮循环的coffee脚本时。

foundKey = null
for key, urls of urlSets
  if 'url-a.com' in urls
    foundKey = key
console.log foundKey #=> a

它使用for key, value of object循环来轻松地在urlSets对象上循环,然后使用if item in array include检查哪个coffee编译为indexOf调用。

您已经尝试使用。。。

 var obj = {a:1, b:2, c:3};
 for (var prop in obj) {
    console.log("o." + prop + " = " + obj[prop]);
 }

如果有用,请参阅:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in