简体   繁体   English

如何循环通过 Javascript object 检查键和值?

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

I have a Javascript object:我有一个 Javascript object:

const mapping = {

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

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

};

I want to iterate through this object and check if the key or the linked_topics (if present) of the object matches a string value.我想遍历这个 object 并检查 object 的keylinked_topics (如果存在)是否与字符串值匹配。

const stringToBeMatched = 'Simplexity'

Code that I tried:我试过的代码:

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

I'm getting the following eslint error with this:我收到以下 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)

How can this be fixed?如何解决这个问题? Is there any better way to achieve this without using for..in?有没有更好的方法可以在不使用 for..in 的情况下实现这一目标?

You can get only the keys using Object.keys您只能使用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}`);
  }
})

Use entries as suggested by ESLint.使用 ESLint 建议的条目。 I used ?.我用过?. instead of .而不是. after "linked_topics" property to prevent Cannot read properties of undefined (reading 'includes') error when no property exists named linked_topics.在“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}`);
  }
})

Good answer from @doctorgu, you could also you some . @doctorgu 的好答案,你可以。

 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM