1

So I have an object, say

 var obj = {
   flowers: { 
            rose: 'red',
            sunflower: 'yellow',
         },

   vegetables: { ... }

 }

Is there anyway to get the keypath for red to return as obj['flowers']['rose'] ? (There are no possibility of duplicate values or keys in my actual object so that wont be a problem)

I have tried to use Object.keys, but that outputs everything since it doesnt have an option to put specific values.

Tried to use for loop, but it would have worked if the nest was just at single level.

I have also tried looking for similar questions, but couldn't make out anything from them. Please throw some light.

1 Answers1

-1

Use a recursive function which iterates over the keys and values. When the value is found, return the key. When a child object is found, call the function recursively, and if the recursive call gives a result, return it:

var obj = {
  flowers: {
    rose: 'red',
    sunflower: 'yellow',
  },

  vegetables: {
  }

};

const findPath = (parentObj, valueToFind) => {
  for (const [key, value] of Object.entries(parentObj)) {
    if (value === valueToFind) return '.' + key;
    if (typeof value === 'object' && value !== null) {
      const possibleResult = findPath(value, valueToFind);
      if (possibleResult) return '.' + key + possibleResult;
    }
  }
};
console.log('obj' + findPath(obj, 'red'));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Thanks a lot, this works like charm, however only for strings/numbers, can you please modify it so that it can work with objects and arrays as well ? - Say, to find the path of flowers. Thanks again, Idk why people downvote such answers -_- – Subrata Rabidas Apr 07 '20 at 06:17
  • Objects and arrays can't be compared with `===`. If you need to implement that sort of comparison, use something like https://stackoverflow.com/questions/1068834/object-comparison-in-javascript – CertainPerformance Apr 07 '20 at 06:19