通过值搜索嵌套对象时,如何找到以句点分隔的键



给定我有一些带有嵌套对象的对象:

const someDataObject = {
places: {
earthKingdom: {
capital: "Ba Sing Se"
},
fireNation: {
capital: "Capital City"
},
waterTribe: {
capital: "North Pole"
}
}
}

我想通过文本搜索来确定属性的完整点分隔键。因此,如果我搜索";"北极";,我的预期结果是";places.waterTribe.capital;

我该如何编写一个函数来完成此操作?

您可以使用recursive函数来实现它。

一旦函数找到值,它将返回一个ary。

每一步都将返回以unshift为关键字的递归。

function findPath(input, word) {
for (let key in input) {
if (input[key] && typeof(input[key]) === "object") {
const result = findPath(input[key], word);
if (result) {
result.unshift(key);
return result;
}
} else if (input[key] === word) {
return [ key ];
}
}
}
const someDataObject = {
places: {
earthKingdom: {
capital: "Ba Sing Se"
},
fireNation: {
capital: "Capital City"
},
waterTribe: {
capital: "North Pole"
}
}
}
const path = findPath(someDataObject, "North Pole");
console.log(path.join('.'));

最新更新