1

is there anyway in JavaScript to print complete path of a nested object attribute. For example assume I have a below object

var items = [ {
  2019 : {
   December: {
      Groceries : {
        KitchenNeeds : {
         [
          "Milk",
          "cheese"
          ]
        }
      }
    }
  }
}];

To access Milk, I can access as items[0].2019.December.Groceries.KitchenNeeds[0] But is there any way, if I choose "Milk" it should print all the tree path thats needs to be travelled to get "Milk".

Raja G
  • 5,973
  • 14
  • 49
  • 82
  • it is possible, but why? – Shashank Dec 16 '19 at 09:59
  • Does this answer your question? https://stackoverflow.com/a/8790711/4449191 – jared Dec 16 '19 at 10:00
  • @Shashank, I have a big list of JSON object like above. So Everytime when I want to read some value, Its kind of getting hard as it is too much nested. – Raja G Dec 16 '19 at 10:01
  • As jared mentioned refer this solution https://stackoverflow.com/questions/8790607/javascript-json-get-path-to-given-subnode/8790711#8790711 but add additional condition for type Array and additional logic to find index of key in the array. – Shashank Dec 16 '19 at 10:02

1 Answers1

1

You could check the if the nested getting the pathe returns a truthy value and return an array with the actual key and the path of the nested value.

function getPath(object, target) {
    var path;
    if (object && typeof object === 'object') {
        Object.entries(object).some(([k, v]) => {
            if (v === target) return path = [k];
            var temp = getPath(v, target);
            if (temp) return path = [k, ...temp];
        });        
    }
    return path;
}

var items = [{ 2019: { December: { Groceries: { KitchenNeeds: ["Milk", "cheese"] } } } }];

console.log(getPath(items, 'Milk'));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392