慕桂英4014372
2023-09-14 17:58:47
我有一個(gè)深層嵌套的對(duì)象const myObject = { a: { b: { c: [ { t: {finallyHere: 'no!'} }, { d: {finallyHere: 'yes!'} }, ] } }}我的輸出對(duì)象看起來像,output = [a, b, c, 1, d] 我將傳遞的函數(shù)是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貢獻(xiàn)1806條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以采用迭代和遞歸方法來檢查值是否是對(duì)象以及鍵是否存在。
如果不是,則迭代鍵并返回,如果函數(shù)的嵌套調(diào)用返回真值并立即返回。
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'));
添加回答
舉報(bào)
0/150
提交
取消