【问题标题】:How do I loop through Javascript object checking key and values?如何循环通过 Javascript 对象检查键和值?
【发布时间】:2022-01-24 09:51:50
【问题描述】:

我有一个 Javascript 对象:

const mapping = {

  'Mind Management': {
    type: 'average',
    linked_topics: ['Digital Detox', 'Small Scaling', 'Simplexity'],
    edge: 'Zeroed Out'
  },

  'Ancient Wisdom': {
    type: 'direct',
    edge: 'Roots Revival'
  }

};

我想遍历这个对象并检查对象的keylinked_topics(如果存在)是否与字符串值匹配。

const stringToBeMatched = 'Simplexity'

我尝试过的代码:

for (var key in mapping) {
  if(key === stringToBeMatched || mapping[key].linked_topics.includes(stringToBeMatched) ) {
    console.log(`found ${stringToBeMatched} in ${key}`);
  }
}

我收到以下 eslint 错误:

ESLint: for..in loops iterate over the entire prototype chain, which is virtually never what you want. Use Object.{keys,values,entries}, and iterate over the resulting array.(no-restricted-syntax)

如何解决这个问题?有没有更好的方法可以在不使用 for..in 的情况下实现这一点?

【问题讨论】:

标签: javascript object eslint


【解决方案1】:

您只能使用Object.keys获取密钥

const keys = Object.keys(mapping);

keys.forEach((key) => {
  if(key === stringToBeMatched || mapping[key].linked_topics.includes(stringToBeMatched) ) {
    console.log(`found ${stringToBeMatched} in ${key}`);
  }
})

【讨论】:

    【解决方案2】:

    使用 ESLint 建议的条目。 我在“linked_topics”属性之后使用?. 而不是.,以防止在不存在名为linked_topics 的属性时出现Cannot read properties of undefined (reading 'includes') 错误。

    const stringToBeMatched = 'Simplexity' 
    
    Object.entries(mapping).forEach(([key, value]) => {
      if(key === stringToBeMatched || value.linked_topics?.includes(stringToBeMatched) ) {
        console.log(`found ${stringToBeMatched} in ${key}`);
      }
    })
    

    【讨论】:

      【解决方案3】:

      @doctorgu 的回答很好,你也可以some

      const string = 'Simplexity'
      
      const mapping = {
        'Mind Management': {
          type: 'average',
          linked_topics: ['Digital Detox', 'Small Scaling', 'Simplexity'],
          edge: 'Zeroed Out'
        },
        'Ancient Wisdom': {
          type: 'direct',
          edge: 'Roots Revival'
        }
      }
      
      const isStringInMapping = Object.entries(mapping).some(([key, value]) => (
          key == string || value.linked_topics?.includes(string)
      ))
      
      console.log(isStringInMapping)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-23
        • 2017-01-28
        • 2017-07-18
        • 1970-01-01
        • 1970-01-01
        • 2021-12-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多