Search code examples
javascriptlodash

Iterate over nested JSON objects and append data to variable


i'm pretty new with JS and i'm struggling a little bit with iterating over a nested JSON object.

I need to grab the value of each nested Node_Subtask_Success in history and save that to a variable I can access later.

The dataset is rather large so I won't add it directly into this post, but i've uploaded it to pastebin here: https://pastebin.com/puZ77V0K

What i've tried so far:

updateData: function() {
                axios
                .get('http://localhost/api/node/839b6556940b19cf9651d0ff7ed08c1154d42b8ef2ef0bda92ffd188d9c82aa0600504389a10f54429c6f83d8cfd58c3e9be1598a4592f37ddd8cd3b3adb9cba')
                .then((response) => {
                    _.each(response.data, function(node) {
                      for(var num in response.data.history) {
                        console.log(num.Node_Subtask_Success)
                      }
                    });
                })
            },

But the above just prints undefined 269 times.


Solution

  • The reason behind that is for..in will pick up the property name in that way:

    The for...in statement iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable properties.

    What you can do instead:

    const history = [
      {
          "id": 539,
          "Node_Cores": 1,
          "Node_Subtask_Success": 856,
      }
    ];
    
    history.forEach(e => {
       console.log(e.Node_Subtask_Success);
    });

    See an example why it was not working:

    const history = [
      {
          "id": 539,
          "Node_Cores": 1,
          "Node_Subtask_Success": 856,
      }
    ];
    
    for (var num in history) {
      console.log({num}); // this return 0
      console.log(num.Node_Subtask_Success); // this one undefined
    }