0

I have an object that looks as below;

{
    "containers": [
        {
            "fields" : {
                "fields": {
                    "fields": {},
                    "prop1": {},
                    "prop2": {}
                },
                "prop1": {},
                "prop2": {}
            }
        },
        {
            "fields" : {
                "fields": {
                    "fields": {},
                    "prop1": {},
                    "prop2": {}
                },
                "prop1": {},
                "prop2": {}
            }
        }       
    ]
}

Now the "fields" is getting repeated inside "fields". I want all the inner "fields" to be removed.

So it should be updated to below;

{
    "containers": [
        {
            "fields" : {
                "prop1": {},
                "prop2": {}
            }
        },
        {
            "fields" : {
                "prop1": {},
                "prop2": {}
            }
        }       
    ]
}

How can I do that? Is it possible to do a delete while iterating over "containers" in a forEach loop or any other way ?

PS: I want to fix the cicrcular dependency (not detect if it is there)

copenndthagen
  • 49,230
  • 102
  • 290
  • 442

1 Answers1

0

Iterating over properties could be done so:

for (var property in object) {
    if (object.hasOwnProperty(property)) {
        // do stuff
    }
}

Iterating over properties requires this additional hasOwnProperty check. It's necessary because an object's prototype contains additional properties for the object which are technically part of the object. Here you cold also check any condition you want.