NodeJS : Loop through nested JSON and remove elements based on a conditionRemove empty elements from an array in JavascriptRemove a JSON attributeHow can I access and process nested objects, arrays or JSON?How to get JSON element type with Gson?Loop through JSON in EJSPass certain parameters from an array of objectshow to process json post request with nodejs http (no express framework)?Remove element from an array based on it's multiple peopertiesJson object to string checking during while loop breaks pagehow to acess json attributes and elements

Ensuring all network services on a device use strong TLS cipher suites

Do they have Supervillain(s)?

Position a tabular on the corner of a slide

What would be the challenges to taking off and landing a typical passenger jet at FL300?

Are modern clipless shoes and pedals that much better than toe clips and straps?

LeetCode: Group Anagrams C#

Why are non-collision-resistant hash functions considered insecure for signing self-generated information

What to say to a student who has failed?

What is this symbol: semicircles facing each other?

Handling Disruptive Student on the Autistic Spectrum

Can a Rogue PC teach an NPC to perform Sneak Attack?

Why in most German places is the church the tallest building?

Why do gliders have bungee cords in the control systems and what do they do? Are they on all control surfaces? What about ultralights?

Why would an IIS hosted site prompt for AD account credential if accessed through a hostname or IP, but not through servername?

The Knight's estate

How do I get a decreased-by-one x in a foreach loop?

Why isn't "I've" a proper response?

“T” in subscript in formulas

How to gently end involvement with an online community?

Would it be possible to have a GMO that produces chocolate?

How would you identify when an object in a Lissajous orbit needs station keeping?

Was it ever possible to target a zone?

French abbreviation for comparing two items ("vs")

Nothing like a good ol' game of ModTen



NodeJS : Loop through nested JSON and remove elements based on a condition


Remove empty elements from an array in JavascriptRemove a JSON attributeHow can I access and process nested objects, arrays or JSON?How to get JSON element type with Gson?Loop through JSON in EJSPass certain parameters from an array of objectshow to process json post request with nodejs http (no express framework)?Remove element from an array based on it's multiple peopertiesJson object to string checking during while loop breaks pagehow to acess json attributes and elements






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















Let's say I have a below object:




"schema": [

"field": "name",
"type": "String",
"enabled": true
,

"field": "age",
"type": "Int",
"enabled": false
,

"field": "modelObj",
"type": "object",
"enabled": true,
"stuff": [

"name": "mod1",
"type": "array",
"enabled": true
,

"name": "mod2",
"type": "String",
"enabled": false
,

"name": "mod3",
"type": "array",
"enabled": true

]
,

"name": "modelArr",
"type": "array",
"enabled": false,
"elements":
"elementsType": "String"

,

"name": "modelsNestedArr",
"type": "array",
"enabled": true,
"elements":
"elementsType": "object"
,
"stuff": [

"name": "name",
"type": "String",
"enabled": true
,

"name": "models",
"type": "array",
"enabled": false,
"elements":
"elementsType": "String"


]

]



I want to loop through this object recursively, and based on if "enabled" is false, remove that item.



So expected Output is:



[

"field": "name",
"type": "String",
"enabled": true
,

"field": "modelObj",
"type": "object",
"enabled": true,
"stuff": [

"name": "mod1",
"type": "array",
"enabled": true
,

"name": "mod3",
"type": "array",
"enabled": true

]
,

"name": "modelsNestedArr",
"type": "array",
"enabled": true,
"elements":
"elementsType": "object"
,
"stuff": [

"name": "name",
"type": "String",
"enabled": true

]

]


I have written the code as below:



function r(a)
for (i = a.length - 1; i >= 0; --i)
if(!a[i].enabled)
a.splice(i,1)
else if (a[i].enabled)
if(a[i].type == "object")
if(a[i])
a[i].stuff= r(a[i].stuff)

else if (a[i].type == "array")
if(a[i].hasOwnProperty("elements") && a[i].elements.elementsType== "object")
a[i].stuff= r(a[i].stuff)





return a


var final = r(a.schema)
console.log(JSON.stringify(final))


But with this I get the below output:



Errored Output:



[

"field": "name",
"type": "String",
"enabled": true
,

"field": "age",
"type": "Int",
"enabled": false
,

"field": "modelObj",
"type": "object",
"enabled": true,
"stuff": [

"name": "mod1",
"type": "array",
"enabled": true
,

"name": "mod2",
"type": "String",
"enabled": false
,

"name": "mod3",
"type": "array",
"enabled": true

]
,

"name": "modelArr",
"type": "array",
"enabled": false,
"elements":
"elementsType": "String"

,

"name": "modelsNestedArr",
"type": "array",
"enabled": true,
"elements":
"elementsType": "object"
,
"stuff": [

"name": "name",
"type": "String",
"enabled": true

]

]


WHat exactly am I doing wrong?










share|improve this question
































    1















    Let's say I have a below object:




    "schema": [

    "field": "name",
    "type": "String",
    "enabled": true
    ,

    "field": "age",
    "type": "Int",
    "enabled": false
    ,

    "field": "modelObj",
    "type": "object",
    "enabled": true,
    "stuff": [

    "name": "mod1",
    "type": "array",
    "enabled": true
    ,

    "name": "mod2",
    "type": "String",
    "enabled": false
    ,

    "name": "mod3",
    "type": "array",
    "enabled": true

    ]
    ,

    "name": "modelArr",
    "type": "array",
    "enabled": false,
    "elements":
    "elementsType": "String"

    ,

    "name": "modelsNestedArr",
    "type": "array",
    "enabled": true,
    "elements":
    "elementsType": "object"
    ,
    "stuff": [

    "name": "name",
    "type": "String",
    "enabled": true
    ,

    "name": "models",
    "type": "array",
    "enabled": false,
    "elements":
    "elementsType": "String"


    ]

    ]



    I want to loop through this object recursively, and based on if "enabled" is false, remove that item.



    So expected Output is:



    [

    "field": "name",
    "type": "String",
    "enabled": true
    ,

    "field": "modelObj",
    "type": "object",
    "enabled": true,
    "stuff": [

    "name": "mod1",
    "type": "array",
    "enabled": true
    ,

    "name": "mod3",
    "type": "array",
    "enabled": true

    ]
    ,

    "name": "modelsNestedArr",
    "type": "array",
    "enabled": true,
    "elements":
    "elementsType": "object"
    ,
    "stuff": [

    "name": "name",
    "type": "String",
    "enabled": true

    ]

    ]


    I have written the code as below:



    function r(a)
    for (i = a.length - 1; i >= 0; --i)
    if(!a[i].enabled)
    a.splice(i,1)
    else if (a[i].enabled)
    if(a[i].type == "object")
    if(a[i])
    a[i].stuff= r(a[i].stuff)

    else if (a[i].type == "array")
    if(a[i].hasOwnProperty("elements") && a[i].elements.elementsType== "object")
    a[i].stuff= r(a[i].stuff)





    return a


    var final = r(a.schema)
    console.log(JSON.stringify(final))


    But with this I get the below output:



    Errored Output:



    [

    "field": "name",
    "type": "String",
    "enabled": true
    ,

    "field": "age",
    "type": "Int",
    "enabled": false
    ,

    "field": "modelObj",
    "type": "object",
    "enabled": true,
    "stuff": [

    "name": "mod1",
    "type": "array",
    "enabled": true
    ,

    "name": "mod2",
    "type": "String",
    "enabled": false
    ,

    "name": "mod3",
    "type": "array",
    "enabled": true

    ]
    ,

    "name": "modelArr",
    "type": "array",
    "enabled": false,
    "elements":
    "elementsType": "String"

    ,

    "name": "modelsNestedArr",
    "type": "array",
    "enabled": true,
    "elements":
    "elementsType": "object"
    ,
    "stuff": [

    "name": "name",
    "type": "String",
    "enabled": true

    ]

    ]


    WHat exactly am I doing wrong?










    share|improve this question




























      1












      1








      1








      Let's say I have a below object:




      "schema": [

      "field": "name",
      "type": "String",
      "enabled": true
      ,

      "field": "age",
      "type": "Int",
      "enabled": false
      ,

      "field": "modelObj",
      "type": "object",
      "enabled": true,
      "stuff": [

      "name": "mod1",
      "type": "array",
      "enabled": true
      ,

      "name": "mod2",
      "type": "String",
      "enabled": false
      ,

      "name": "mod3",
      "type": "array",
      "enabled": true

      ]
      ,

      "name": "modelArr",
      "type": "array",
      "enabled": false,
      "elements":
      "elementsType": "String"

      ,

      "name": "modelsNestedArr",
      "type": "array",
      "enabled": true,
      "elements":
      "elementsType": "object"
      ,
      "stuff": [

      "name": "name",
      "type": "String",
      "enabled": true
      ,

      "name": "models",
      "type": "array",
      "enabled": false,
      "elements":
      "elementsType": "String"


      ]

      ]



      I want to loop through this object recursively, and based on if "enabled" is false, remove that item.



      So expected Output is:



      [

      "field": "name",
      "type": "String",
      "enabled": true
      ,

      "field": "modelObj",
      "type": "object",
      "enabled": true,
      "stuff": [

      "name": "mod1",
      "type": "array",
      "enabled": true
      ,

      "name": "mod3",
      "type": "array",
      "enabled": true

      ]
      ,

      "name": "modelsNestedArr",
      "type": "array",
      "enabled": true,
      "elements":
      "elementsType": "object"
      ,
      "stuff": [

      "name": "name",
      "type": "String",
      "enabled": true

      ]

      ]


      I have written the code as below:



      function r(a)
      for (i = a.length - 1; i >= 0; --i)
      if(!a[i].enabled)
      a.splice(i,1)
      else if (a[i].enabled)
      if(a[i].type == "object")
      if(a[i])
      a[i].stuff= r(a[i].stuff)

      else if (a[i].type == "array")
      if(a[i].hasOwnProperty("elements") && a[i].elements.elementsType== "object")
      a[i].stuff= r(a[i].stuff)





      return a


      var final = r(a.schema)
      console.log(JSON.stringify(final))


      But with this I get the below output:



      Errored Output:



      [

      "field": "name",
      "type": "String",
      "enabled": true
      ,

      "field": "age",
      "type": "Int",
      "enabled": false
      ,

      "field": "modelObj",
      "type": "object",
      "enabled": true,
      "stuff": [

      "name": "mod1",
      "type": "array",
      "enabled": true
      ,

      "name": "mod2",
      "type": "String",
      "enabled": false
      ,

      "name": "mod3",
      "type": "array",
      "enabled": true

      ]
      ,

      "name": "modelArr",
      "type": "array",
      "enabled": false,
      "elements":
      "elementsType": "String"

      ,

      "name": "modelsNestedArr",
      "type": "array",
      "enabled": true,
      "elements":
      "elementsType": "object"
      ,
      "stuff": [

      "name": "name",
      "type": "String",
      "enabled": true

      ]

      ]


      WHat exactly am I doing wrong?










      share|improve this question
















      Let's say I have a below object:




      "schema": [

      "field": "name",
      "type": "String",
      "enabled": true
      ,

      "field": "age",
      "type": "Int",
      "enabled": false
      ,

      "field": "modelObj",
      "type": "object",
      "enabled": true,
      "stuff": [

      "name": "mod1",
      "type": "array",
      "enabled": true
      ,

      "name": "mod2",
      "type": "String",
      "enabled": false
      ,

      "name": "mod3",
      "type": "array",
      "enabled": true

      ]
      ,

      "name": "modelArr",
      "type": "array",
      "enabled": false,
      "elements":
      "elementsType": "String"

      ,

      "name": "modelsNestedArr",
      "type": "array",
      "enabled": true,
      "elements":
      "elementsType": "object"
      ,
      "stuff": [

      "name": "name",
      "type": "String",
      "enabled": true
      ,

      "name": "models",
      "type": "array",
      "enabled": false,
      "elements":
      "elementsType": "String"


      ]

      ]



      I want to loop through this object recursively, and based on if "enabled" is false, remove that item.



      So expected Output is:



      [

      "field": "name",
      "type": "String",
      "enabled": true
      ,

      "field": "modelObj",
      "type": "object",
      "enabled": true,
      "stuff": [

      "name": "mod1",
      "type": "array",
      "enabled": true
      ,

      "name": "mod3",
      "type": "array",
      "enabled": true

      ]
      ,

      "name": "modelsNestedArr",
      "type": "array",
      "enabled": true,
      "elements":
      "elementsType": "object"
      ,
      "stuff": [

      "name": "name",
      "type": "String",
      "enabled": true

      ]

      ]


      I have written the code as below:



      function r(a)
      for (i = a.length - 1; i >= 0; --i)
      if(!a[i].enabled)
      a.splice(i,1)
      else if (a[i].enabled)
      if(a[i].type == "object")
      if(a[i])
      a[i].stuff= r(a[i].stuff)

      else if (a[i].type == "array")
      if(a[i].hasOwnProperty("elements") && a[i].elements.elementsType== "object")
      a[i].stuff= r(a[i].stuff)





      return a


      var final = r(a.schema)
      console.log(JSON.stringify(final))


      But with this I get the below output:



      Errored Output:



      [

      "field": "name",
      "type": "String",
      "enabled": true
      ,

      "field": "age",
      "type": "Int",
      "enabled": false
      ,

      "field": "modelObj",
      "type": "object",
      "enabled": true,
      "stuff": [

      "name": "mod1",
      "type": "array",
      "enabled": true
      ,

      "name": "mod2",
      "type": "String",
      "enabled": false
      ,

      "name": "mod3",
      "type": "array",
      "enabled": true

      ]
      ,

      "name": "modelArr",
      "type": "array",
      "enabled": false,
      "elements":
      "elementsType": "String"

      ,

      "name": "modelsNestedArr",
      "type": "array",
      "enabled": true,
      "elements":
      "elementsType": "object"
      ,
      "stuff": [

      "name": "name",
      "type": "String",
      "enabled": true

      ]

      ]


      WHat exactly am I doing wrong?







      node.js json recursion nested iteration






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 27 at 18:44







      user1452759

















      asked Mar 27 at 17:25









      user1452759user1452759

      2,34911 gold badges30 silver badges47 bronze badges




      2,34911 gold badges30 silver badges47 bronze badges

























          4 Answers
          4






          active

          oldest

          votes


















          2















          A recursive function using .map() and .filter() will make your life easier:



           function isEnabledRecursive(data)
          return data.filter(
          item=>item.enabled
          )
          .map(
          item=>item.stuff?Object.assign(item,stuff:isEnabledRecursive(item.stuff))
          :item
          );

          const dataWithFilteredSchema = Object.assign(data, schema:isEnabledRecursive(data.schema))


          This will work to any depth.



          It does assume that all your arrays are in the stuff property. If you had other properties with arrays of objects in them you'd have to cycle through each property with something like for(property of item) to see if they had an array in them.



          As for why your original code isn't working, nothing in your else if statements are running. When you say a[i].type or a[i].dataType it is undefined. You probably meant to say typeof a[i] === "object" and typeof a[i] === "array"






          share|improve this answer



























          • This helped me a lot. I need to read up on map and filter better. Thank you!

            – user1452759
            Mar 27 at 18:42


















          1















          From my observations, either your schema object is inconsistent or the function.
          Your schema object has both type and dataType keys. I'm considering all of it as type, and here is the solution.



          With your splice implementation, the array was subjected to change amidst the loop and might skip few indices.



          E.g. if the array was,



          [
          name: 'mod1', enabled: false,
          name: 'mod2', enabled: true,
          name: 'mod3', enabled: true
          ]


          After the deletion of index 0, array length becomes 2 instead of 3. Hence, one less element will be accessed.



          Hence I included another object deleteIndices to mark the indices for deletion after the completion of the loop.




          BTW, you can always choose map and filter to make this way
          simpler.




          function r(a) 
          let deleteIndices = ;
          for (let i = 0; i < a.length; i++)
          if (!a[i].enabled)
          deleteIndices[i] = true;
          else
          if (a[i].type == "object")
          a[i].stuff = r(a[i].stuff)
          else if (a[i].type == "array" && a[i].elements && a[i].elements.elementsType == "object")
          a[i].stuff = r(a[i].stuff)




          a = a.filter((e, index) => !deleteIndices[index])
          return a;


          schema = r(schema)





          share|improve this answer



























          • Sorry. Fixed the question

            – user1452759
            Mar 27 at 18:44











          • No problem. I guess the above example was good enough to understand the mistake.

            – Chinmaya Pati
            Mar 27 at 18:47


















          0















          Let's name a your array (object.schema), then the result can be obtained like this:



          var result = a.filter(element => element.enabled).map(element => );


          Be careful, sometimes you have dataType and sometimes you have types as field name.



          You should use map and filter.
          Very simple to write and use.



          Docs: map, filter






          share|improve this answer



























          • nitpick: in the example a is an object not an array.

            – Phil
            Mar 27 at 17:52











          • ´a´ corresponds to ´object.schema´

            – thibautj
            Mar 27 at 17:59











          • This will work on the data the questioner provided but only to depth of 1. If the items in 'stuff' have their own 'stuff' array in them then they won't be filtered. Not sure if that matters to the questioner.

            – jimboweb
            Mar 27 at 18:23











          • The 'stuff' can be to any depth, nested within itself.

            – user1452759
            Mar 27 at 18:33











          • Also, I have fixed the question regarding 'type' and 'dataType'

            – user1452759
            Mar 27 at 18:45


















          0















          The most simple and sweet solution i could think and will work for any depth






          function r(arr)
          let filtered = arr.filter((obj)=>
          return obj.enabled;
          );
          return filtered.map((obj)=>
          if(obj.stuff)
          obj.stuff = r(obj.stuff)
          return obj
          )

          result = r(a.schema)
          console.log(JSON.stringify(result,null,2))








          share|improve this answer



























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55383207%2fnodejs-loop-through-nested-json-and-remove-elements-based-on-a-condition%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            4 Answers
            4






            active

            oldest

            votes








            4 Answers
            4






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            2















            A recursive function using .map() and .filter() will make your life easier:



             function isEnabledRecursive(data)
            return data.filter(
            item=>item.enabled
            )
            .map(
            item=>item.stuff?Object.assign(item,stuff:isEnabledRecursive(item.stuff))
            :item
            );

            const dataWithFilteredSchema = Object.assign(data, schema:isEnabledRecursive(data.schema))


            This will work to any depth.



            It does assume that all your arrays are in the stuff property. If you had other properties with arrays of objects in them you'd have to cycle through each property with something like for(property of item) to see if they had an array in them.



            As for why your original code isn't working, nothing in your else if statements are running. When you say a[i].type or a[i].dataType it is undefined. You probably meant to say typeof a[i] === "object" and typeof a[i] === "array"






            share|improve this answer



























            • This helped me a lot. I need to read up on map and filter better. Thank you!

              – user1452759
              Mar 27 at 18:42















            2















            A recursive function using .map() and .filter() will make your life easier:



             function isEnabledRecursive(data)
            return data.filter(
            item=>item.enabled
            )
            .map(
            item=>item.stuff?Object.assign(item,stuff:isEnabledRecursive(item.stuff))
            :item
            );

            const dataWithFilteredSchema = Object.assign(data, schema:isEnabledRecursive(data.schema))


            This will work to any depth.



            It does assume that all your arrays are in the stuff property. If you had other properties with arrays of objects in them you'd have to cycle through each property with something like for(property of item) to see if they had an array in them.



            As for why your original code isn't working, nothing in your else if statements are running. When you say a[i].type or a[i].dataType it is undefined. You probably meant to say typeof a[i] === "object" and typeof a[i] === "array"






            share|improve this answer



























            • This helped me a lot. I need to read up on map and filter better. Thank you!

              – user1452759
              Mar 27 at 18:42













            2














            2










            2









            A recursive function using .map() and .filter() will make your life easier:



             function isEnabledRecursive(data)
            return data.filter(
            item=>item.enabled
            )
            .map(
            item=>item.stuff?Object.assign(item,stuff:isEnabledRecursive(item.stuff))
            :item
            );

            const dataWithFilteredSchema = Object.assign(data, schema:isEnabledRecursive(data.schema))


            This will work to any depth.



            It does assume that all your arrays are in the stuff property. If you had other properties with arrays of objects in them you'd have to cycle through each property with something like for(property of item) to see if they had an array in them.



            As for why your original code isn't working, nothing in your else if statements are running. When you say a[i].type or a[i].dataType it is undefined. You probably meant to say typeof a[i] === "object" and typeof a[i] === "array"






            share|improve this answer















            A recursive function using .map() and .filter() will make your life easier:



             function isEnabledRecursive(data)
            return data.filter(
            item=>item.enabled
            )
            .map(
            item=>item.stuff?Object.assign(item,stuff:isEnabledRecursive(item.stuff))
            :item
            );

            const dataWithFilteredSchema = Object.assign(data, schema:isEnabledRecursive(data.schema))


            This will work to any depth.



            It does assume that all your arrays are in the stuff property. If you had other properties with arrays of objects in them you'd have to cycle through each property with something like for(property of item) to see if they had an array in them.



            As for why your original code isn't working, nothing in your else if statements are running. When you say a[i].type or a[i].dataType it is undefined. You probably meant to say typeof a[i] === "object" and typeof a[i] === "array"







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 27 at 18:44

























            answered Mar 27 at 18:11









            jimbowebjimboweb

            2,0882 gold badges11 silver badges29 bronze badges




            2,0882 gold badges11 silver badges29 bronze badges















            • This helped me a lot. I need to read up on map and filter better. Thank you!

              – user1452759
              Mar 27 at 18:42

















            • This helped me a lot. I need to read up on map and filter better. Thank you!

              – user1452759
              Mar 27 at 18:42
















            This helped me a lot. I need to read up on map and filter better. Thank you!

            – user1452759
            Mar 27 at 18:42





            This helped me a lot. I need to read up on map and filter better. Thank you!

            – user1452759
            Mar 27 at 18:42













            1















            From my observations, either your schema object is inconsistent or the function.
            Your schema object has both type and dataType keys. I'm considering all of it as type, and here is the solution.



            With your splice implementation, the array was subjected to change amidst the loop and might skip few indices.



            E.g. if the array was,



            [
            name: 'mod1', enabled: false,
            name: 'mod2', enabled: true,
            name: 'mod3', enabled: true
            ]


            After the deletion of index 0, array length becomes 2 instead of 3. Hence, one less element will be accessed.



            Hence I included another object deleteIndices to mark the indices for deletion after the completion of the loop.




            BTW, you can always choose map and filter to make this way
            simpler.




            function r(a) 
            let deleteIndices = ;
            for (let i = 0; i < a.length; i++)
            if (!a[i].enabled)
            deleteIndices[i] = true;
            else
            if (a[i].type == "object")
            a[i].stuff = r(a[i].stuff)
            else if (a[i].type == "array" && a[i].elements && a[i].elements.elementsType == "object")
            a[i].stuff = r(a[i].stuff)




            a = a.filter((e, index) => !deleteIndices[index])
            return a;


            schema = r(schema)





            share|improve this answer



























            • Sorry. Fixed the question

              – user1452759
              Mar 27 at 18:44











            • No problem. I guess the above example was good enough to understand the mistake.

              – Chinmaya Pati
              Mar 27 at 18:47















            1















            From my observations, either your schema object is inconsistent or the function.
            Your schema object has both type and dataType keys. I'm considering all of it as type, and here is the solution.



            With your splice implementation, the array was subjected to change amidst the loop and might skip few indices.



            E.g. if the array was,



            [
            name: 'mod1', enabled: false,
            name: 'mod2', enabled: true,
            name: 'mod3', enabled: true
            ]


            After the deletion of index 0, array length becomes 2 instead of 3. Hence, one less element will be accessed.



            Hence I included another object deleteIndices to mark the indices for deletion after the completion of the loop.




            BTW, you can always choose map and filter to make this way
            simpler.




            function r(a) 
            let deleteIndices = ;
            for (let i = 0; i < a.length; i++)
            if (!a[i].enabled)
            deleteIndices[i] = true;
            else
            if (a[i].type == "object")
            a[i].stuff = r(a[i].stuff)
            else if (a[i].type == "array" && a[i].elements && a[i].elements.elementsType == "object")
            a[i].stuff = r(a[i].stuff)




            a = a.filter((e, index) => !deleteIndices[index])
            return a;


            schema = r(schema)





            share|improve this answer



























            • Sorry. Fixed the question

              – user1452759
              Mar 27 at 18:44











            • No problem. I guess the above example was good enough to understand the mistake.

              – Chinmaya Pati
              Mar 27 at 18:47













            1














            1










            1









            From my observations, either your schema object is inconsistent or the function.
            Your schema object has both type and dataType keys. I'm considering all of it as type, and here is the solution.



            With your splice implementation, the array was subjected to change amidst the loop and might skip few indices.



            E.g. if the array was,



            [
            name: 'mod1', enabled: false,
            name: 'mod2', enabled: true,
            name: 'mod3', enabled: true
            ]


            After the deletion of index 0, array length becomes 2 instead of 3. Hence, one less element will be accessed.



            Hence I included another object deleteIndices to mark the indices for deletion after the completion of the loop.




            BTW, you can always choose map and filter to make this way
            simpler.




            function r(a) 
            let deleteIndices = ;
            for (let i = 0; i < a.length; i++)
            if (!a[i].enabled)
            deleteIndices[i] = true;
            else
            if (a[i].type == "object")
            a[i].stuff = r(a[i].stuff)
            else if (a[i].type == "array" && a[i].elements && a[i].elements.elementsType == "object")
            a[i].stuff = r(a[i].stuff)




            a = a.filter((e, index) => !deleteIndices[index])
            return a;


            schema = r(schema)





            share|improve this answer















            From my observations, either your schema object is inconsistent or the function.
            Your schema object has both type and dataType keys. I'm considering all of it as type, and here is the solution.



            With your splice implementation, the array was subjected to change amidst the loop and might skip few indices.



            E.g. if the array was,



            [
            name: 'mod1', enabled: false,
            name: 'mod2', enabled: true,
            name: 'mod3', enabled: true
            ]


            After the deletion of index 0, array length becomes 2 instead of 3. Hence, one less element will be accessed.



            Hence I included another object deleteIndices to mark the indices for deletion after the completion of the loop.




            BTW, you can always choose map and filter to make this way
            simpler.




            function r(a) 
            let deleteIndices = ;
            for (let i = 0; i < a.length; i++)
            if (!a[i].enabled)
            deleteIndices[i] = true;
            else
            if (a[i].type == "object")
            a[i].stuff = r(a[i].stuff)
            else if (a[i].type == "array" && a[i].elements && a[i].elements.elementsType == "object")
            a[i].stuff = r(a[i].stuff)




            a = a.filter((e, index) => !deleteIndices[index])
            return a;


            schema = r(schema)






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 27 at 18:45

























            answered Mar 27 at 18:37









            Chinmaya PatiChinmaya Pati

            213 bronze badges




            213 bronze badges















            • Sorry. Fixed the question

              – user1452759
              Mar 27 at 18:44











            • No problem. I guess the above example was good enough to understand the mistake.

              – Chinmaya Pati
              Mar 27 at 18:47

















            • Sorry. Fixed the question

              – user1452759
              Mar 27 at 18:44











            • No problem. I guess the above example was good enough to understand the mistake.

              – Chinmaya Pati
              Mar 27 at 18:47
















            Sorry. Fixed the question

            – user1452759
            Mar 27 at 18:44





            Sorry. Fixed the question

            – user1452759
            Mar 27 at 18:44













            No problem. I guess the above example was good enough to understand the mistake.

            – Chinmaya Pati
            Mar 27 at 18:47





            No problem. I guess the above example was good enough to understand the mistake.

            – Chinmaya Pati
            Mar 27 at 18:47











            0















            Let's name a your array (object.schema), then the result can be obtained like this:



            var result = a.filter(element => element.enabled).map(element => );


            Be careful, sometimes you have dataType and sometimes you have types as field name.



            You should use map and filter.
            Very simple to write and use.



            Docs: map, filter






            share|improve this answer



























            • nitpick: in the example a is an object not an array.

              – Phil
              Mar 27 at 17:52











            • ´a´ corresponds to ´object.schema´

              – thibautj
              Mar 27 at 17:59











            • This will work on the data the questioner provided but only to depth of 1. If the items in 'stuff' have their own 'stuff' array in them then they won't be filtered. Not sure if that matters to the questioner.

              – jimboweb
              Mar 27 at 18:23











            • The 'stuff' can be to any depth, nested within itself.

              – user1452759
              Mar 27 at 18:33











            • Also, I have fixed the question regarding 'type' and 'dataType'

              – user1452759
              Mar 27 at 18:45















            0















            Let's name a your array (object.schema), then the result can be obtained like this:



            var result = a.filter(element => element.enabled).map(element => );


            Be careful, sometimes you have dataType and sometimes you have types as field name.



            You should use map and filter.
            Very simple to write and use.



            Docs: map, filter






            share|improve this answer



























            • nitpick: in the example a is an object not an array.

              – Phil
              Mar 27 at 17:52











            • ´a´ corresponds to ´object.schema´

              – thibautj
              Mar 27 at 17:59











            • This will work on the data the questioner provided but only to depth of 1. If the items in 'stuff' have their own 'stuff' array in them then they won't be filtered. Not sure if that matters to the questioner.

              – jimboweb
              Mar 27 at 18:23











            • The 'stuff' can be to any depth, nested within itself.

              – user1452759
              Mar 27 at 18:33











            • Also, I have fixed the question regarding 'type' and 'dataType'

              – user1452759
              Mar 27 at 18:45













            0














            0










            0









            Let's name a your array (object.schema), then the result can be obtained like this:



            var result = a.filter(element => element.enabled).map(element => );


            Be careful, sometimes you have dataType and sometimes you have types as field name.



            You should use map and filter.
            Very simple to write and use.



            Docs: map, filter






            share|improve this answer















            Let's name a your array (object.schema), then the result can be obtained like this:



            var result = a.filter(element => element.enabled).map(element => );


            Be careful, sometimes you have dataType and sometimes you have types as field name.



            You should use map and filter.
            Very simple to write and use.



            Docs: map, filter







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 27 at 17:56

























            answered Mar 27 at 17:42









            thibautjthibautj

            364 bronze badges




            364 bronze badges















            • nitpick: in the example a is an object not an array.

              – Phil
              Mar 27 at 17:52











            • ´a´ corresponds to ´object.schema´

              – thibautj
              Mar 27 at 17:59











            • This will work on the data the questioner provided but only to depth of 1. If the items in 'stuff' have their own 'stuff' array in them then they won't be filtered. Not sure if that matters to the questioner.

              – jimboweb
              Mar 27 at 18:23











            • The 'stuff' can be to any depth, nested within itself.

              – user1452759
              Mar 27 at 18:33











            • Also, I have fixed the question regarding 'type' and 'dataType'

              – user1452759
              Mar 27 at 18:45

















            • nitpick: in the example a is an object not an array.

              – Phil
              Mar 27 at 17:52











            • ´a´ corresponds to ´object.schema´

              – thibautj
              Mar 27 at 17:59











            • This will work on the data the questioner provided but only to depth of 1. If the items in 'stuff' have their own 'stuff' array in them then they won't be filtered. Not sure if that matters to the questioner.

              – jimboweb
              Mar 27 at 18:23











            • The 'stuff' can be to any depth, nested within itself.

              – user1452759
              Mar 27 at 18:33











            • Also, I have fixed the question regarding 'type' and 'dataType'

              – user1452759
              Mar 27 at 18:45
















            nitpick: in the example a is an object not an array.

            – Phil
            Mar 27 at 17:52





            nitpick: in the example a is an object not an array.

            – Phil
            Mar 27 at 17:52













            ´a´ corresponds to ´object.schema´

            – thibautj
            Mar 27 at 17:59





            ´a´ corresponds to ´object.schema´

            – thibautj
            Mar 27 at 17:59













            This will work on the data the questioner provided but only to depth of 1. If the items in 'stuff' have their own 'stuff' array in them then they won't be filtered. Not sure if that matters to the questioner.

            – jimboweb
            Mar 27 at 18:23





            This will work on the data the questioner provided but only to depth of 1. If the items in 'stuff' have their own 'stuff' array in them then they won't be filtered. Not sure if that matters to the questioner.

            – jimboweb
            Mar 27 at 18:23













            The 'stuff' can be to any depth, nested within itself.

            – user1452759
            Mar 27 at 18:33





            The 'stuff' can be to any depth, nested within itself.

            – user1452759
            Mar 27 at 18:33













            Also, I have fixed the question regarding 'type' and 'dataType'

            – user1452759
            Mar 27 at 18:45





            Also, I have fixed the question regarding 'type' and 'dataType'

            – user1452759
            Mar 27 at 18:45











            0















            The most simple and sweet solution i could think and will work for any depth






            function r(arr)
            let filtered = arr.filter((obj)=>
            return obj.enabled;
            );
            return filtered.map((obj)=>
            if(obj.stuff)
            obj.stuff = r(obj.stuff)
            return obj
            )

            result = r(a.schema)
            console.log(JSON.stringify(result,null,2))








            share|improve this answer





























              0















              The most simple and sweet solution i could think and will work for any depth






              function r(arr)
              let filtered = arr.filter((obj)=>
              return obj.enabled;
              );
              return filtered.map((obj)=>
              if(obj.stuff)
              obj.stuff = r(obj.stuff)
              return obj
              )

              result = r(a.schema)
              console.log(JSON.stringify(result,null,2))








              share|improve this answer



























                0














                0










                0









                The most simple and sweet solution i could think and will work for any depth






                function r(arr)
                let filtered = arr.filter((obj)=>
                return obj.enabled;
                );
                return filtered.map((obj)=>
                if(obj.stuff)
                obj.stuff = r(obj.stuff)
                return obj
                )

                result = r(a.schema)
                console.log(JSON.stringify(result,null,2))








                share|improve this answer













                The most simple and sweet solution i could think and will work for any depth






                function r(arr)
                let filtered = arr.filter((obj)=>
                return obj.enabled;
                );
                return filtered.map((obj)=>
                if(obj.stuff)
                obj.stuff = r(obj.stuff)
                return obj
                )

                result = r(a.schema)
                console.log(JSON.stringify(result,null,2))








                function r(arr)
                let filtered = arr.filter((obj)=>
                return obj.enabled;
                );
                return filtered.map((obj)=>
                if(obj.stuff)
                obj.stuff = r(obj.stuff)
                return obj
                )

                result = r(a.schema)
                console.log(JSON.stringify(result,null,2))





                function r(arr)
                let filtered = arr.filter((obj)=>
                return obj.enabled;
                );
                return filtered.map((obj)=>
                if(obj.stuff)
                obj.stuff = r(obj.stuff)
                return obj
                )

                result = r(a.schema)
                console.log(JSON.stringify(result,null,2))






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 27 at 18:41









                Vikash SinghVikash Singh

                1,4522 gold badges8 silver badges25 bronze badges




                1,4522 gold badges8 silver badges25 bronze badges






























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55383207%2fnodejs-loop-through-nested-json-and-remove-elements-based-on-a-condition%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                    은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현