0

Is it possible to remove the circular type that is inside an object?

let say

result = {
a : [Array],
b : [Object],
c : [Circular],
d : 'string'
e : {
  x : [Circular],
  y : {
    z : [Circular]
    }
}
}

to

result = {
    a : [Array],
    b : [Object],
    d : 'string'
    }

I wanted to filter out all the circular type within the objects.

Attempt 1:

Since the name for each object is also the same in the children object. I tried to delete it since most children circular object only points to the parents. (actually, I got confused on this part). Here is the code i tried to use.

let keys = Object.keys(obj)
keys.forEach(val => {
    if (obj[val] instanceof Object || obj[val] instanceof Array) {
        Object.values(obj[val]).filter(function (value, index, arr) {
            if (keys.indexOf(Object.keys(value)[index]) > 0) {
                delete obj[val][index]
            }
        })
    }
})
Daniel Mana
  • 9,451
  • 13
  • 29
  • 41
  • Yes, what have you tried? – James May 05 '19 at 09:57
  • 1
    Take this function and adapt it to remove the properties: https://stackoverflow.com/a/14962496/5768908 – Gerardo Furtado May 05 '19 at 10:06
  • i tried https://stackoverflow.com/a/40293777/9506054 and stackoverflow.com/a/14962496/5768908 and modified it to delete the circular type directly, but it just give me "Maximum call stack size exceeded" – Daniel Mana May 05 '19 at 10:29

1 Answers1

0

You could use a Set to filter out objects that are seen twice:

const noCirculars = v => {
  const set = new Set; 
  const noCirculars = v => {
    if(Array.isArray(noCirculars))
      return v.map(noCirculars);
    if(typeof v === "object" && v !== null) {
      if(set.has(v)) return undefined;
      set.add(v);

      return Object.fromEntries(Object.entries(v)
       .map(([k, v]) => ([k, noCirculars(v)])));
    }
    return v;
  };
  return noCirculars(v);
};
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151