How to access values by key from modified React final form

Viewed 166

I was making confirmation when the user tried to close the form by modified and values length > 0.

if (modified) {
    return (
      Object.keys(modified).filter(
        (modifiedItem) => modified[modifiedItem]  && values[modifiedItem]?.length > 0,
      ).length > 0
    )
  }

Everything is working fine until there are values with an array: when I try to access by values[answers.0.icon] there is undefined, of course, it should be accessed by values.answers[0].icon, by is it possible to do it when iterating modified keys? Or another way should be appreciated.

Thank you beforehand.

Below screenshots of values:

enter image description here

Modified keys:

enter image description here

3 Answers

you could add undefined and null in the if statement, to check if it's true and not undefined and not null before it filter else it will be null or you can put something else.

if (modified && modified !== undefined && modified !== null) {
 return (
  Object.keys(modified).filter(
    (modifiedItem) => modified[modifiedItem]  && values[modifiedItem]?.length > 0,
  ).length > 0
 )   
} 
else {
 null
}

I'd suggest to include lodash and use the get function. This will resolve the "path" for you.

For example _.get(values, modifiedItem).

More info can be found at https://lodash.com/docs/4.17.15#get

You can perhaps check for such situation if its an array and treat it differently.

I agree with solution provided by @Stijn answer, however if you dont wanna carry unnecessary baggage of Lodash you can use below code.

const parseDeep = (obj, path, def) => (() => typeof path === 'string' ? 
  path.replace(/\[(\d+)]/g,'.$1') : path.join('.'))()
  .split('.')
  .filter(Boolean)
  .every(step => ((obj = obj[step]) !== undefined)) ? obj : def

if (modified) {
return (
  Object.keys(modified).filter(
    (modifiedItem) => 
      Array.isArray(modifiedItem) ?
      modified[modifiedItem] && parseDeep(values, modifiedItem, false) : //modify as required
      modified[modifiedItem]  && values[modifiedItem]?.length > 0,
  ).length > 0
)
}
Related