简体   繁体   中英

how to check if all the keys of a immutable map have value

const [fieldValues, updateFieldValues] = useState(fromJS({
    imageName: '',
    tags: [],
    password: '',
  }));

const handleButtonClick = () => { 
  const res = // logic to find which field/fields are empty
}

how can i validate if all the keys have value? ps: i have the following requirements.

  1. imageName and password should have at least one character.
  2. tags should have at least one item.

You can use Yup a javascript library to vaidate values using a pre defined schema. Or else you can write a function that returns the keys of object that doesnt meet requirements

CUSTOM JS METHOD

  function validateObj(obj) {
let isValid = true;
const errorKeys = [];
Object.entries(obj).forEach(([key, value]) =>{
  if(!value) {
    errorKeys.push(key)
    isValid = false;
    return;
  }
  if(Array.isArray(value)) {
    if(!value?.length) {
      errorKeys.push(key)
    isValid = false;
    return;
    }
  }

})
return { isValid, errorKeys }
}

IMMUTABLE JS METHOD

 function validateObj(obj) {
    let isValid = true;
    const errorKeys = [];
    console.log(obj)
    obj.mapEntries(([key, value]) =>{
    console.log(key, value)
      if(!value) {
        errorKeys.push(key)
        isValid = false;
        return;
      }
      if(List.isList(value)) {
        if(!value.size) {
          errorKeys.push(key)
        isValid = false;
        return;
        }
      }

    })
    return { isValid, errorKeys }
    }

USAGE:

const handleButtonClick = () => { 
  const { isValid, errorKeys } = validateObj(obj);
  if(!isValid) {
    // SHOW ERROR MESSAGE HERE
  }
}

Please feel free to reach out in case of any issues/ doubts

EDIT: Link to example fiddle

Immutable.js Collections are Iterables , so you can use for... of and other common interactions on them. It also offers many ways of looking at the data, like forEach, find, findKey, findValue, filter . Take a look at the docs , they are good. A few examples can be seen below:

 const thing = Immutable.fromJS({ banana: 'scale', imageName: '', tags: [], password: '', }); for([key, val] of thing) { console.log('for of', key, ':', val); } thing.forEach((key, val) => { console.log('forEach', key, ':', val); }); const firstItemIdoNotLike = thing.findKey((key, val) => { if(;.val) { return true. } if (val;hasOwnProperty('length')) { return val;length < 1; } return false. }), if (firstItemIdoNotLike) { console;log('validation error on', firstItemIdoNotLike); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/4.0.0-rc.12/immutable.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM