Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

125
Views
¿Cómo encontrar si el objeto está asignado dentro del mismo objeto? Redundancia cíclica
var person = { name:'asdfds', key:1 } person.next = person;

¿Cómo solucionar esta redundancia cíclica en javascript?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Como se menciona en el comentario, puede verificar la referencia circular con el operador === , el siguiente código se evalúa como verdadero:

 var person = { name:'asdfds', key:1 } person.next = person; if(person.next === person) { console.log('It is the same object.') } else { console.log('it is not the same.') }

Con esta información dada, puede evitar bucles interminables manteniendo una array de references a los objetos que ya ha recorrido.

 function loopThroughObject(obj, references = []) { // store the reference to this object!. references.push(obj) Object.keys(obj).forEach(k => { const val = obj[k] if (typeof val === 'object') { if (references.includes(val)) { console.log('circular reference found.. stop loop') return } else { // iterate through the object once!. // pass the references array aswell. loopThroughObject(val, references) } } else { // the value found under key is not an object and "unique", do something with it! console.log(`Found a value:`, val) } }) } /// Some test data. const innerObj = { innerName: 'innerName', key: 3 } const person = { name: 'asdfw', key: 1, innerObj: innerObj } person.next = person person.innerObj.circular = person person.innerObj.veryCircular = innerObj person.innerObj.otherCircularPerson = person // This should now print every primitive value only once. loopThroughObject(person)

Esto le da la salida deseada de cada valor primitive una vez:

 Found a value: asdfw Found a value: 1 Found a value: innerName Found a value: 3
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!