Gold100
Gold100

Reputation: 124

how to not print multiple times?

I had a task to print out all the fields of a given object and i solved it like this:

function print(jsonObject) {
     if (typeof(jsonObject) === 'object') {
        for (var prop in Object.keys(jsonObject)) {
            if (typeof(jsonObject[prop]) === 'object') {
                print(jsonObject[prop]);
            }else{
                 console.log(prop + ':' + jsonObject[prop]);
            }
        }
    }
}

But what do I do if i had an object refrenced to one another? like so:

let one = {
    name: 'name',
    age: 21
}

let two = {
    name: {
        firstName: 'name',
        lastName: 'lastname'
    }
    age: 22,
}

two.ref = one
one.ref = two;

What is the stop condition? thanks

Upvotes: 0

Views: 50

Answers (1)

user120242
user120242

Reputation: 15268

Simple naive reference lookup, that checks if the same object has been traversed using a WeakSet().
Will have false positives on property values that reference the same object.
eg: one.ref1=one.ref

printer(one)

function printer(jsonObject) {
  const seen = new WeakSet();
  print(jsonObject)
  function print(jsonObject) {
     if (typeof(jsonObject) === 'object') {
        if(jsonObject) seen.add(jsonObject);
        for (var prop of Object.keys(jsonObject)) {
            if (typeof(jsonObject[prop]) === 'object') {
                if(jsonObject[prop]!==null) {
                  if(seen.has(jsonObject[prop])) {
                    console.log(`circular ref at key ${prop}:`,jsonObject[prop]);
                    return;
                  }
                  else
                    print(jsonObject[prop]);
                  seen.add(jsonObject[prop]);
                }
            }else{
                 console.log(prop + ':' + jsonObject[prop]);
            }
        }
    }
  }
}
<script>
let one = {
    name: 'name',
    age: 21
}

let two = {
    name: {
        firstName: 'name',
        lastName: 'lastname'
    },
    age: 22,
}

two.ref = one;
one.ref = two;
</script>

Upvotes: 1

Related Questions