10

I have a JSON input which can go to any number of levels.

I'm giving an input sample of

var d=getEntities( {"Categories": 
{
"Facets": 
    [
    {
    "count": 1,
    "entity": "Company",
    "Company": 
            [
            {

            "entity": "Ford Motor Co",

            "Ford_Motor_Co": 
                [
                    {
                    "count": 1,
                    "entity": "Ford"
                    }
                ]
            }
            ]
    },
        {
            "count": 4,
            "entity": "Country",
              "Country": [
                    {

                        "entity": "Germany",
                         "Germany": [
                                {
                                    "count": 1,
                                    "entity": "Germany"
                                }
                          ],
                        "currency": "Euro (EUR)"
                    },
                    {

                         "entity": "Italy",
                        "Italy": [
                                {
                                     "count": 1,
                                     "entity": "Italy"
                                }
                          ],
                        "currency": "Euro (EUR)"
                    },
                    {

                        "entity": "Japan",
                          "Japan": [
                             {
                                    "count": 1,
                                    "entity": "Japan"
                             }
                          ],
                        "currency": "Yen (JPY)"
                    },
                    {

                        "entity": "South Korea",
                          "South_Korea": [
                              {
                                    "count": 1,
                                    "entity": "South Korea"
                                }
                          ],
                      "currency": "Won (KRW)"
                    }
              ]
        },
        {"count": 5,
              "entity": "Persons",
              "Persons": [
                    {
                         "count": 2,
                        "entity": "Dodge"
                    },
                    {
                        "count": 1,
                        "entity": "Dodge Avenger"
                    },
                    {
                        "count": 1,
                        "entity": "Major League"
                    },
                    {
                        "count": 1,
                        "entity": "Sterling Heights"
                    }
              ]
        }
  ]

}});

I want to add the key value "Entity" in all levels to an array using recursion,

I'm able to collect the data from first level using the string

<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript" src="dataDumper.js"></script>


<script type="text/javascript">

var testJSON = {"Categories": 
{
"Facets": 
    [
    {
    "count": 1,
    "entity": "Company",
    "Company": 
            [
            {

            "entity": "Ford Motor Co",

            "Ford_Motor_Co": 
                [
                    {
                    "count": 1,
                    "entity": "Ford"
                    }
                ]
            }
            ]
    },
        {
            "count": 4,
            "entity": "Country",
              "Country": [
                    {

                        "entity": "Germany",
                         "Germany": [
                                {
                                    "count": 1,
                                    "entity": "Germany"
                                }
                          ],
                        "currency": "Euro (EUR)"
                    },
                    {

                         "entity": "Italy",
                        "Italy": [
                                {
                                     "count": 1,
                                     "entity": "Italy"
                                }
                          ],
                        "currency": "Euro (EUR)"
                    },
                    {

                        "entity": "Japan",
                          "Japan": [
                             {
                                    "count": 1,
                                    "entity": "Japan"
                             }
                          ],
                        "currency": "Yen (JPY)"
                    },
                    {

                        "entity": "South Korea",
                          "South_Korea": [
                              {
                                    "count": 1,
                                    "entity": "South Korea"
                                }
                          ],
                      "currency": "Won (KRW)"
                    }
              ]
        },
        {"count": 5,
              "entity": "Persons",
              "Persons": [
                    {
                         "count": 2,
                        "entity": "Dodge"
                    },
                    {
                        "count": 1,
                        "entity": "Dodge Avenger"
                    },
                    {
                        "count": 1,
                        "entity": "Major League"
                    },
                    {
                        "count": 1,
                        "entity": "Sterling Heights"
                    }
              ]
        }
  ]

}};

function scan(obj)
{
    var k;
    if (obj.hasOwnProperty('entity')) {



        for (k in obj){
           if (obj.hasOwnProperty(k)){


                scan( obj[k] );  


            }                
          }
    } 


    else{
        if(k=='entity')
        {
        alert(obj.entity);
   }
    }


};

scan(testJSON);



</script>
</head>

<body>

</body>

</html>

How do I get in to the inner levels for JSON string using recursive functions?

6
  • Dont put an else in, put the if and alert before the call to scan Commented May 6, 2012 at 15:32
  • Thumbs up!!! And thanks a lot!!!! Really appreciate all your help.. Commented May 6, 2012 at 23:14
  • @ElRonnoco Ive been experimenting with this thing and do u knw hw we cn add entities in different levels in to same array.. ie entities in level 1 goes to one array, level 2 to nxt and so on.. Commented May 7, 2012 at 3:47
  • I'm not clear what you mean. You can add any new property to a Json object just by saying eg Main.new=1 will create a property 'new' in object Main. If you want to create a new Json object use {}. To create an array use []. to add a Json object to an array use myarray.push({}). To add an array to an array use myarray.push([]) Commented May 7, 2012 at 11:21
  • with out using "key", do you know how to perform the same operation using array... Commented May 7, 2012 at 11:24

5 Answers 5

22

I have made a jsfiddle which traverses every object,array and value in the JS object like so...

function scan(obj) {
    var k;
    if (obj instanceof Object) {
        for (k in obj){
            if (obj.hasOwnProperty(k)){
                //recursive call to scan property
                scan( obj[k] );  
            }                
        }
    } else {
        //obj is not an instance of Object so obj here is a value
    };

};

I get no recursion error (in Chrome). Can you use this to do what you want?

If you need to test if an object is an array use if (obj instanceof Array)

To test if an object has an "entity" property use if (obj.hasOwnProperty('entity'))

To add (or modify an existing) "entity" property use obj.entity = value or obj['entity'] = value

Sign up to request clarification or add additional context in comments.

15 Comments

I've answered this on my iPhone so if someone could fix my formatting i'd be very grateful!!!
its showing the error,if is nt defined for If (h.hasOwnProperty(k))
Ah you may new to test for 'if (h instanceof object)' before entering the loop.
no,,,it ws the format of ur code...I was in big letter.. It now alerts first entity Company and then shows "too much recursion " for getEntities(h[k]);
The "stop expression" is the one I used in my answer: if ( ({}).toString.apply( prop ) === '[object Object]' ) {. Btw, Object.keys returns an array of the enumerable properties, so it is not needed to use hasOwnProperty.
|
1
(function recur( obj ) {
    Object.keys( obj ).forEach( function( prop ) {
        // Check if the property is an object
        if ( ({}).toString.apply( prop ) === '[object Object]' ) {
            // If it is, recall this function
            recur( prop );
        }
    } );
} () );

I haven't added your logic, but you get the idea of how to recursively traverse your object.

8 Comments

how do I add the value of subobj here for the above example?
What? I don't understand your comment.
Oops, edited my answer correcly. The subobj is the property of the object that is an object, so you can traverse it too.
one more doubt, for recursion for this doubt. what If I want to get the value Ford Motor Co, I can do it this way h.Categories.Facets[0].Company[0].entity or I take the value Company using h.Categories.Facets[0].entity and then how do I append the value Company in to "h.Categories.Facets[[0]. '()' .entity" line..
I'm not sure I got you, but are you looking for: h.Categories.Facets[[0]. '()' .entity = h.Categories.Facets[0].Company[0].entity? The first part is clearly not good, but I don't know what you mean.
|
1

Say I have a structure like the following:

var aObject = {
    items: [],
    children: {}
}

Children is an associative array that contains more aObjects. So it could look like this:

var aObject = {
    items: [],
    children: {
        "subgroup1": {
            items: [],
            children: {}
        },
        "subgroup2": {
            items: [],
            children: {}
        }
    }
}

I have an item that contains an array of subgroups:

["subgroup1", "subgroup1a"]

Each subgroup is a 'location'. The item needs to be placed at:

aObject.children[array[0]].children[array[1]].items

At each level, we have to check if children[array[i]] exists, and if not, create it. You can't simply write aObject.children[array[0]].children[array[1]].items.push(item) because children[array[0]] might not already exist and we will get an error.

This can be solved using recursion! (AngularJS)

function recursive(aLevel, aItem, aArray, aIndex){
    var lLevel = aLevel;

    // If we have reached the end of the array
    if (aIndex === aArray.length){
        // Insert
        aLevel.items.push(aItem);
    } else {

        // If the subgroup doesn't exist, create it
        if (typeof aLevel.children[aArray[aIndex]] === 'undefined'){
            aLevel.children[aArray[aIndex]] = {
              items: [],
              children: {}
            };
        }

        // Move into
        recursive(aLevel.children[aArray[aIndex]], aItem, aArray, aIndex+1);
    }
}

aObject = {
    items: [],
    children: {},
}

angular.forEach(items, function(item, i){
    var location = item.location;

    if (location.length == 0){
        aObject.items.push(item);
    } else {
        recursive(aObject, item, location, 0);
    }
});

The final aObject would look like this:

var aObject = {
     items: [],
     children: {
        "subgroup1": {
            items: [],
            children: {
                "subgroup1a": {
                    items: [item],
                    children: {}
                }
            }
        },
        "subgroup2": {
            items: [],
            children: {}
        }
    }
}

Comments

1

Here is a function that i use often. It's easily modifiable to do many recursive tasks. For example if you add a bail flag you can quickly get the stack or add a callback function that makes it even more general. Anyway that's my 2 cents

var recursiveObjMap = (function(){
  var stack = [];
  var result = [];
  // var bail = false;
  return function map(data, key){
    if (!$.isArray(data) && !$.isPlainObject(data) ) { 
      result.push(data);
      return false 
    }

    $.each(data, function(i, v){
      if (key) stack.push(key);
      map(v, i);
      stack.pop();
    });
    return result;
  };
})();

recursiveObjMap({a:'b',c:{d:{e:"f"}}}) // ['b', 'f']

Comments

0
const obj = [
  {
    count: 1,
    entity: "Company",
    Company: [
      {
        entity: "Ford Motor Co",

        Ford_Motor_Co: [
          {
            count: 1,
            entity: "Ford",
          },
        ],
      },
    ],
  },
  {
    count: 4,
    entity: "Country",
    Country: [
      {
        entity: "Germany",
        Germany: [
          {
            count: 1,
            entity: "Germany",
          },
        ],
        currency: "Euro (EUR)",
      },
      {
        entity: "Italy",
        Italy: [
          {
            count: 1,
            entity: "Italy",
          },
        ],
        currency: "Euro (EUR)",
      },
      {
        entity: "Japan",
        Japan: [
          {
            count: 1,
            entity: "Japan",
          },
        ],
        currency: "Yen (JPY)",
      },
      {
        entity: "South Korea",
        South_Korea: [
          {
            count: 1,
            entity: "South Korea",
          },
        ],
        currency: "Won (KRW)",
      },
    ],
  },
  {
    count: 5,
    entity: "Persons",
    Persons: [
      {
        count: 2,
        entity: "Dodge",
      },
      {
        count: 1,
        entity: "Dodge Avenger",
      },
      {
        count: 1,
        entity: "Major League",
      },
      {
        count: 1,
        entity: "Sterling Heights",
      },
    ],
  },
];
function test(runObj) {
  for (let i in runObj) {
    typeof runObj[i] == "object" ? test(runObj[i]) : console.log(runObj[i]);
  }
}
test(obj);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.