【问题标题】:Iterate over an object and find the key [duplicate]遍历一个对象并找到键[重复]
【发布时间】:2021-11-15 16:18:32
【问题描述】:

假设我有这个数据集

let data = {
  1: ['item1', '3435'],
  32: ['item2', '5465'],
  16: ['item3', '6577']
}

现在我想找到包含数字“3435”的密钥。 为此,我找不到迭代对象的方法。有没有不使用迭代的方法找到匹配项?

findKey(3534) // should return "1"
findKey(6577) // should return "16"

【问题讨论】:

  • 它是否总是需要成为数组的第二个元素?或者只是数组中的任何元素?
  • 第二个元素@Ivar
  • 使用this,但将object[key]改为object[key][1]
  • 还要注意 JSON != 一个 JavaScript 对象。

标签: javascript


【解决方案1】:

也许你可以这样迭代。不确定我们是否可以在不迭代的情况下实现这一目标。

const getKey = (matchString) => {
  let data = {
    1: ['item1', '3435'],
    32: ['item2', '5465'],
    16: ['item3', '6577']
  }

  for (let item in data) {
    if (data[item].includes(matchString)) {
      return item;
    }
  }
}

const key = getKey('3435')
console.log(key)

【讨论】:

    【解决方案2】:

    一个可能的解决方案是:

     let data = {
      1 : ['item1', '3435'],
      32 : ['item2', '5465'],
      16 : ['item3', '6577']
    }
    
    for (const [key, value] of Object.entries(data)) {  
      if(value.includes('3435'))  
      {
        console.log(key)
      }
    }

    【讨论】:

      【解决方案3】:

      function searchByKey(data,Sval){
        let output
        Object.entries(data).forEach(each=>{
          let key = each[0] , val = each[1][1]
          if(Sval == val){output = each[0]}
        })
        return output
      }
       
       
      let data = {
          1 : ['item1', '3435'],
          32 : ['item2', '5465'],
          16 : ['item3', '6577']
        }
      
      let s = searchByKey(data,"5465")
      
      console.log(s)
      注意此函数仅适用于您当前的数据结构

      【讨论】:

        【解决方案4】:

        您可以利用Object.entries() 方法来检索密钥。

        const data = {
          1: ["item1", "3435"],
          32: ["item2", "5465"],
          16: ["item3", "6577"]
        };
        
        const getMatchingKey = (num) => {
          return Object.entries(data).filter(([key, value]) => value[1] === num)[0];
          // if you need all matching keys, remove the 0th index ===============^^^
        };
        
        const [key] = getMatchingKey("3435");
        console.log(key);

        【讨论】:

          【解决方案5】:

          您不能直接遍历 JSON,但可以使用 Object.keys() 获取键列表。

          从那里,他们有两个选择:

          如果您知道只有一个值匹配,请使用循环返回选定的值

          function findInObject(value) {
            for (let i in Object.keys(data)) {
              if (data[i][1] == value) {
                return i
              }
            }
          }
          

          返回16

          如果可能有多个条目,请使用filter()

          function findInObject(value) {
            return Object.keys(data.filter(elem => elem[1] == value))
          }
          

          返回[16, 42, 1000]

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-06-10
            • 2015-09-15
            • 1970-01-01
            • 2019-01-26
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多