如何遍历 Javascript 对象检查键和值?

How do I loop through Javascript object checking key and values?

我有一个 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?

您只能使用 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}`);
  }
})

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

@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)