假设我们有一个这样的对象-
const obj = { "name": "Vivek Sharma", "occupation": "Software Engineer", "age": 23, "contacts": [{ "name": "Mukul Sharma", "occupation": "Software Engineer", "age": 31, }, { "name": "Jay Sharma", "occupation": "Software Engineer", "age": 27, }, { "name": "Rajan Sharma", "occupation": "Software Engineer", "age": 32, }] };
在这里,它最多只能嵌套一层,但是嵌套也可以更深。我们需要编写一个对象函数Object.prototype.keysOf(),该函数接受一个值并返回具有参数中指定值的所有键的数组。
因此,现在让我们编写此函数的代码-
const obj = { "name": "Vivek Sharma", "occupation": "Software Engineer", "age": 23, "contacts": [{ "name": "Mukul Sharma", "occupation": "Software Engineer", "age": 31, }, { "name": "Jay Sharma", "occupation": "Software Engineer", "age": 27, }, { "name": "Rajan Sharma", "occupation": "Software Engineer", "age": 32, }] }; const keysOf = function(val, obj = this, res = []){ const keys = Object.keys(obj); for(let ind = 0; ind < keys.length; ind++){ if(obj[keys[ind]] === val){ res.push(keys[ind]); }else if(typeof obj[keys[ind]] === 'object' && !Array.isArray(obj[keys[ind]])){ keysOf(val, obj[keys[ind]], res); }; }; return res; }; Object.prototype.keysOf = keysOf; console.log(obj.keysOf(23));
输出结果
控制台中的输出将为-
['age']