How to make this function return an array with keys. Here is the code for this function itself:

Object.prototype.getKeyByValue = function(value, objs) { if (!objs) objs = []; for (var prop in this) { if (this.hasOwnProperty(prop)) { if (this[prop] === value) { return prop; } else if(typeof this[prop] === "object" && objs.indexOf(this[prop]) == -1) { objs.push(this[prop]); var res = this[prop].getKeyByValue(value, objs); if (res) return prop + "." + res; } } } } 

This feature works well in this example:

 Object.prototype.getKeyByValue = function(value, objs) { if (!objs) objs = []; for (var prop in this) { if (this.hasOwnProperty(prop)) { if (this[prop] === value) { return prop; } else if (typeof this[prop] === "object" && objs.indexOf(this[prop]) == -1) { objs.push(this[prop]); var res = this[prop].getKeyByValue(value, objs); if (res) return prop + "." + res; } } } } var foobar = { foo: 5, bar: { baz: 3 } //для теста сделаем вложеный объект } document.write(foobar.getKeyByValue(3)); 

However, when a second key appears with the same value, it is not (understand why). You must make getKeyByValue return an array. So how can this be implemented?

  • one
    do the result of the recursion is not return and push - Grundy
  • one
    better change the snippet to reproduce your problem. But not like now - when everything works well - Grundy

1 answer 1

 Object.prototype.getKeysByValue = function (value) { let keys = []; for (let key of Object.keys(this)) { if (this[key] === value) { keys.push(key); } else if (typeof this[key] === 'object') { let keysInner = this[key].getKeysByValue(value); for (let keyInner of keysInner) { keys.push(key + '.' + keyInner); } } } return keys; }; let foobar = { aaa: 7, bbb: 10, ccc: { ddd: 7, eee: { fff: 7, ggg: 10 } } }; console.log(foobar.getKeysByValue(7));