首页  >  文章  >  web前端  >  如何使用字符串路径从深度嵌套对象中检索值?

如何使用字符串路径从深度嵌套对象中检索值?

Barbara Streisand
Barbara Streisand原创
2024-10-24 23:30:30191浏览

How to Retrieve Values from Deeply Nested Objects Using String Paths?

使用字符串路径检索深度嵌套的对象值

问题:

寻求一个从深度嵌套中检索值的函数通过遍历表示嵌套结构的字符串路径来访问对象。例如:

<code class="javascript">var obj = {
  foo: { bar: 'baz' }
};
// Retrieve obj.foo.bar's value with the string "foo.bar"
getValue(obj, "foo.bar");</code>

解决方案:

以下解决方案使用提供的字符串路径有效地导航嵌套对象:

<code class="javascript">function getValue(obj, path) {
  var pathParts = path.split('.');
  for (var i = 0; i < pathParts.length; i++) {
    obj = obj[pathParts[i]];
  }
  return obj;
}</code>

解释:

  1. 字符串路径被拆分为对象键数组(在我们的示例中为 ["foo", "bar"])。
  2. 我们迭代通过数组,检索与每个键关联的值。
  3. 最终结果代表提供的路径处的值。

示例:

<code class="javascript">var obj = {
  foo: { bar: 'baz' }
};
console.log(getValue(obj, "foo.bar")); // Output: "baz"</code>

以上是如何使用字符串路径从深度嵌套对象中检索值?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn