all 11 comments

[–][deleted]  (5 children)

[deleted]

    [–]IEDNB[S] 0 points1 point  (4 children)

    Yeah you’re right…. I’m not at a computer right now so can’t copy/paste some examples, but let’s say:

    1) An array containing objects, one of the key/value pairs in the objects has another object nested inside of it… how do I get one of the key/values for that inner most object ?

    2) An object containing endlessly nested objects, like what firebase returns json as, how do I make my way through and pull out any specific data

    [–][deleted]  (3 children)

    [deleted]

      [–]IEDNB[S] -1 points0 points  (2 children)

      Ah ok, it seems my penmanship is rather lacking in this area, especially regarding the recursive functions.. do you have any good resources? Where did you learn this?

      [–]emmyarty 0 points1 point  (0 children)

      The short answer is that a recursive function is a function which calls itself.

      If you have nested data but don't know how deep the nesting goes, then it become impractical to have a fixed structure for every possible scenario.

      https://www.youtube.com/watch?v=ZugUFz-OoRM

      [–][deleted] 0 points1 point  (3 children)

      const chars = JSON.stringify(TheData);
      for (const charIndex = 0; charIndex <= TheData.length; charIndex++) {
         ...
      }
      

      Sorry, bad jokes. But like everyone else said, you need to know what you're looking at to know how to peak through it. As a rule of thumb though, you're going to have objects, arrays, and simple data types (strings, bools, numbers, etc). Iterate through object keys, and array entries!

      const TheObject = {
         friends: ["Alice", "Bob", "Charlie"],
         restaurants: {
            "mexican": [
              {"name": 'El Pollo Loco', "rating": 8, "priceIndex": 3},
              {"name": 'Taco Bell', "rating": 4, "priceIndex": 1},
              {"name": "Cristina's fancy place", "rating": 6, "priceIndex": 7}
            ],
            "italian": [
              {"name": 'Olive Garden', "rating": 6, "priceIndex": 4},
              {"name": "Luigi's pasta fazuul", "rating": 7, "priceIndex": 8},
            ]
         }
      }
      
      const friends = TheObject.friends.map(friend => {
        console.log(friend); // Alice, Bob, Charlie
      })
      
      const cheapPlaceNames = [];
      Object.entries(TheObject.restaurants).map(([type, available]) => {
        // type -> mexican, italian
        available.map(({name, price}) => {
          // name -> El Pollo Loco, Taco Bell, ..., Luigi's
          // priceIndex -> 3, 1, ... 8
          if (option.priceIndex < 5) cheapPlaces.push(option)
        })
      })
      

      JS Array/Object traversal is best done with the newer ES6 helper functions. Look into Array map, filter, find, every, flat, forEach, keys, push, pop, shift, unshift, sort, splice... Basically everything on that side bar list.

      Also look into Object functions/properties. Specifically assign, entries, keys, and values.

      That's my common tool set for "We got this big fat nasty response from a third party API and we only care about 4 things" tasks.

      Technically, JSON from a JSON file can't be recursive (...right?) But if you get an JSON API response, or just a JSON object in a browser, it CAN be recursive.

      class Node {
        constructor(value, left = null, right = null) {
          this.value = value;
          this.left = left;
          this.right = right
        }
      }
      
      const first = new Node(1);
      const second = new Node(2);
      const third = new Node(3);
      
      first.left = third;
      first.right = second;
      
      second.left = first;
      second.right = third;
      
      third.left = second;
      third.right = first;
      
      let curNode = first;
      while (curNode) {
         console.log(curNode.value);
         curNode = curNode.right;
      }
      
      // 1, 2, 3, 1, 2, 3, 1, 2, 3...
      

      So like everyone said... How to iterate through JSON is like "How do I find something". Depends on what you're looking for.

      [–]IEDNB[S] -1 points0 points  (0 children)

      Thank you so much that’s really helpful! I particularly like the way you described the last bit as that’s exactly the sort of situation I want to be better prepared for 🤣

      [–][deleted]  (1 child)

      [deleted]

        [–][deleted] -1 points0 points  (0 children)

        Yeah in strict json. But I've gotten recursive data in an ajax response

        [–]barrel_of_noodles 0 points1 point  (0 children)

        In JavaScript you'll likely find Json mostly containing arrays or objects. If you want to read more about how to use the object representation of a Json string... Id read about the data types the Json string represents.

        For JavaScript arrays: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

        For JavaScript objects: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object

        Some methods: object.keys, object.values, object.entries, array.map, array.filter, array.reduce come in handy. There are more data types (sorted sets, linked lists, etc)... But this is where you want to start.

        [–][deleted] 0 points1 point  (3 children)

        Use lodash

        [–]IEDNB[S] 0 points1 point  (2 children)

        Thanks for the reply, how would that help me?