Tengo un objeto Javascript:
const mapping = { 'Mind Management': { type: 'average', linked_topics: ['Digital Detox', 'Small Scaling', 'Simplexity'], edge: 'Zeroed Out' }, 'Ancient Wisdom': { type: 'direct', edge: 'Roots Revival' } }; Quiero iterar a través de este objeto y verificar si la key o los linked_topics (si están presentes) del objeto coinciden con un valor de cadena.
const stringToBeMatched = 'Simplexity'
Código que probé:
for (var key in mapping) { if(key === stringToBeMatched || mapping[key].linked_topics.includes(stringToBeMatched) ) { console.log(`found ${stringToBeMatched} in ${key}`); } }Recibo el siguiente error de eslint con esto:
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)¿Cómo se puede arreglar esto? ¿Hay alguna forma mejor de lograr esto sin usar for..in?
Puede obtener solo las claves usando 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}`); } })Utilice las entradas sugeridas por ESLint. usé ?. en lugar . después de la propiedad "linked_topics" para evitar que Cannot read properties of undefined (reading 'includes') cuando no existe una propiedad llamada linked_topics.
const stringToBeMatched = 'Simplexity' Object.entries(mapping).forEach(([key, value]) => { if(key === stringToBeMatched || value.linked_topics?.includes(stringToBeMatched) ) { console.log(`found ${stringToBeMatched} in ${key}`); } })Buena respuesta de @doctorgu, también podrías tener algunos .
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)