如何在React中以编程方式构建对象数据的路径

时间:2018-07-17 18:32:32

标签: javascript reactjs react-redux

我有一个数据对象,如下图所示:

enter image description here

数据来自我的Redux存储,所以当我要显示的是camera_1的IP时,可以通过以下方式访问它:this.props.data.settings.cameras.camera_1.IP._text

我的问题是,如果我要以编程方式构建上面的路径,则会出现错误,因为REACT将路径视为字符串。是的,我知道,我正在使用文字字符串构建路径,但是如何解决问题呢? :-/

这是我尝试构建路径的方法:

const root = this.props.data.settings
// The following strings are coming from the previous page as routing params
const {page,node,item} = this.props.match.params


// The strings have the following values
page = 'cameras'
node = 'camera_1'
item = 'IP'

const fullPath = `${root}.${page}.${node}.${item}._text`

感谢您的宝贵时间和帮助!

谢谢:-)))

2 个答案:

答案 0 :(得分:2)

您可以通过使用变量pagenodeitem作为键来访问对象中的值来获取最终值:

const text = this.props.data.settings[page][node][item]._text;

如果要将路径作为字符串,则可以使用lodash.get

const fullPath = `props.data.settings.${page}.${node}.${item}._text`;
const text = _.get(this, fullPath);

答案 1 :(得分:0)

感谢您的快速答复。 @Tholle回答解决了问题:

您可以通过使用变量页面,节点,项目作为键访问对象中的值来获取最终值:

const text = this.props.data.settings [page] [node] [item] ._ text; 如果要将路径作为字符串,则可以使用lodash.get:

const fullPath = props.data.settings.${page}.${node}.${item}._text; const text = _.get(this,fullPath);