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".

4
  • it is possible, but why? Commented Dec 16, 2019 at 9:59
  • Does this answer your question? stackoverflow.com/a/8790711/4449191 Commented Dec 16, 2019 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. Commented Dec 16, 2019 at 10:01
  • As jared mentioned refer this solution stackoverflow.com/questions/8790607/… but add additional condition for type Array and additional logic to find index of key in the array. Commented Dec 16, 2019 at 10:02

1 Answer 1

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'));

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

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.