1

I need to access the "isTouched" property from a nested object. The challenge is that this property could either be shown like this:

form: { CHANGES: { isTouched: true/false } }

or

form: { 'formName': { isTouched: true/false } }

Accessing the first would straightforward with:

form.CHANGES.isTouched

however, I would like to have one method that can cater for both scenarios also considering that the form name will change based on whatever form is being used.

I thought about collecting all of the form names and loop through them but I think that would be not very effective.

1
  • I am not 100% sure what you mean. I think you want variable instead of hardcoded name. form[variable_name].isTouched can be used in this case. Commented Oct 1, 2018 at 10:23

3 Answers 3

2

I'm not 100% I understand the question, but would something like this work for you?

k = Object.keys(form)[0]
form[k].isTouched
Sign up to request clarification or add additional context in comments.

Comments

1

You can use Object.keys() which will give you an array of object's own property names. Then you can simply access the first object name by using index:

var form = { 'formName': { isTouched: true/false } }
var o = Object.keys(form)[0];
console.log(form[o].isTouched);

Comments

0

Here you are:

/**
* Returns the value of the isTouched property from provided object.
* If formName specified, the value will be retrieved from the o[formName] sub object, otherwise from the default sub object accessed by key CHANGES
*/
function getIsTouched(o, formName){
    return o[formName] ? o[formName].isTouched : o.CHANGES.isTouched
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.