Fernando Martz
Fernando Martz

Reputation: 53

How to build programmatically the path for object data in React

I have a data object that looks like the shot below:

enter image description here

The data is coming from my Redux store, so when I want to display let's say the IP of camera_1, I can reach it the following way: this.props.data.settings.cameras.camera_1.IP._text

My problem is that if I want to build programmatically the path above I get an error because REACT take the path as a string. Yes I know, I'm building the path with literal strings but how to solve the problem? :-/

This is the way I'm trying to build the path:

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`

I appreciate your time and help!

Thanks :-)))

Upvotes: 3

Views: 1129

Answers (2)

Fernando Martz
Fernando Martz

Reputation: 53

Thanks for the quick replies. @Tholle answer solved the problem:

You can get the final value by accessing values in the object with the variables page, node, item as keys:

const text = this.props.data.settings[page][node][item]._text; If you want the path as a string, you could use lodash.get:

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

Upvotes: 0

Tholle
Tholle

Reputation: 112917

You can get the final value by accessing values in the object with the variables page, node, item as keys:

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

If you want the path as a string, you could use lodash.get:

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

Upvotes: 2

Related Questions