我有一个深层嵌套的对象const myObject = { a: { b: { c: [ { t: {finallyHere: 'no!'} }, { d: {finallyHere: 'yes!'} }, ] } }}我的输出对象看起来像,output = [a, b, c, 1, d] 我将传递的函数是getPath(myObject, 'd')到目前为止我正在尝试的功能,function getPath(obj, key) { paths = [] function getPaths(obj, path) { if (obj instanceof Object && !(obj instanceof Array)) { for (var k in obj){ paths.push(path + "." + k) getPaths(obj[k], path + "." + k) } } } getPaths(obj, "") return paths.map(function(p) { return p.slice(p.lastIndexOf(".") + 1) == key ? p.slice(1) : '' }).sort(function(a, b) {return b.split(".").length - a.split(".").length;})[0];}我未定义,请帮助输出
1 回答

慕森卡
TA贡献1806条经验 获得超8个赞
您可以采用迭代和递归方法来检查值是否是对象以及键是否存在。
如果不是,则迭代键并返回,如果函数的嵌套调用返回真值并立即返回。
const
getPath = (o, target) => {
if (!o || typeof o !== 'object') return;
if (target in o) return [target];
for (const k in o) {
const temp = getPath(o[k], target);
if (temp) return [k, ...temp];
}
};
object = { a: { b: { c: [{ t: { finallyHere: 'no!' } }, { d: { finallyHere: 'yes!' } } ] } } };
console.log(getPath(object, 'd'));
添加回答
举报
0/150
提交
取消