使用字符串访问嵌套属性 [英] Access a nested property with a string

查看:114
本文介绍了使用字符串访问嵌套属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var person = {
  name: 'Joe',
  contact: {
    phone: '555'
  }
}

var nameOfPerson = person['name']; //Joe

var str = 'contact.phone';
var phoneToPerson = person[str]; //undefined

这可能以某种方式吗?我得到了一些逻辑,我最终得到一个字符串,我需要用它来访问一个嵌套属性。

Is this possible to do somehow? I got some logic where I end up with a string and I need to access a nested property with it.

https://jsbin.com/xehokozaco/edit?js,console

推荐答案

您必须按句点拆分字符串,然后迭代访问每个节点。这可以通过简单的 reduce 来完成:

You'll have to split the string by the period, and then access each node iteratively. This could be done in a simple reduce:

var value = str.split('.').reduce(function(p,prop) { return p[prop] }, person);

无论 str 是否包含上述内容都可行一段时间与否,即 name 以及 contact.phone

The above would work regardless if str contains a period or not, i.e. for name as well as contact.phone.

这篇关于使用字符串访问嵌套属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆