Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

131
Vistas
How to find if object is assigned inside the same object? cyclic redundancy
var person = {
    name:'asdfds',
    key:1
}

person.next = person;

How to fix this cyclic redundancy in javascript?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

As mentioned in the comment, you can check circular reference with === operator, following code evaluates to true:

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.')
}

With this given information you can avoid looping endlessly by holding an array of references to the objects you have already looped through.


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)

This gives you the desired output of every primitive value once:

Found a value: asdfw
Found a value: 1
Found a value: innerName
Found a value: 3

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda