在 JavaScript 中按值搜索对象
假设我们有一个类似如下的对象 −
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']
广告