首页 文章资讯内容详情

递归列出嵌套对象键JavaScript

2026-06-04 1 花语

假设我们有一个对象,其他对象是它的属性值,它嵌套到2-3级甚至更高。

这是示例对象-

const people = { Ram: { fullName: Ram Kumar, details: { age: 31, isEmployed: true } }, Sourav: { fullName: Sourav Singh, details: { age: 22, isEmployed: false } }, Jay: { fullName: Jay Grewal, details: { age: 26, isEmployed: true } } }

我们的工作是编写一个接受该对象和字符串的函数,在整个对象中搜索该字符串作为键,然后返回一个数组,该数组包含与该字符串匹配的所有键的值

我们将其称为recursiveSearch()函数,考虑到嵌套,递归将是解决这种情况的最合适方法。

因此,此函数recursiveSearch()的完整代码将为-

示例

const people = { Ram: { fullName: Ram Kumar, details: { age: 31, isEmployed: true } }, Sourav: { fullName: Sourav Singh, details: { age: 22, isEmployed: false } }, Jay: { fullName: Jay Grewal, details: { age: 26, isEmployed: true } } } const recursiveSearch = (obj, searchKey, results = []) => { const r = results; Object.keys(obj).forEach(key => { const value = obj[key]; if(key === searchKey && typeof value !== object){ r.push(value); }else if(typeof value === object){ recursiveSearch(value, searchKey, r); } }); return r; }; console.log(recursiveSearch(people, age));

输出结果

控制台中的输出将为-

[ 31, 22, 26 ]

在上面的函数中,首先我们迭代主对象,每当遇到嵌套时,我们就在子对象上递归地迭代搜索所需的键,如果找到所需的键,则立即将其值记录在结果数组中,最后,当我们完成迭代时,我们返回包含所需值的结果数组。

该函数的时间复杂度为O(mn),其中为主要对象内子对象的数量,m为嵌套的最深层。