从javascript对象属性创建路径

编程入门 行业动态 更新时间:2024-10-15 02:24:40
本文介绍了从javascript对象属性创建路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有以下javascript对象

Let's say I've got the following javascript object

var obj = { a:{ b:"value", c:{ d:"value2" } } }

当用"d"对象(例如,function getPath(obj, d))输入时,什么功能输出"a.c.d"字符串?我已经尝试过各种方法,包括对象路径,但它似乎不是设计好的为此

What function would, when input with the "d" object (for example, function getPath(obj, d)), output the "a.c.d" string? I've tried various things including object-path, but it doesn't seem to be designed for that

推荐答案

您可以使用迭代和递归方法.

You could use an iterative and recursive approach.

function getPath(object, key) { function iter(o, p) { if (typeof o === 'object') { return Object.keys(o).some(function (k) { return iter(o[k], p.concat(k)); }); } if (p[p.length - 1] === key) { path = p; return true; } } var path = []; iter(object, []); return path.join('.'); } console.log(getPath({ d: { d: { d: { d: 'val' } } } }, 'd')); console.log(getPath({ a: { b: 'value', c: { d: 'value2' } } }, 'd'));

.as-console-wrapper { max-height: 100% !important; top: 0; }

更多推荐

从javascript对象属性创建路径

本文发布于:2023-11-24 12:42:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1625245.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路径   属性   对象   javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!