简体   繁体   中英

Want to return true or false when finding an exact match in an array of objects?

I have a posList that contains an array of objects. I want to check if the entered value is an exact match of all the posCode in each object of the posList. My RegExp returns true when its a search match. For example, when 4325 is entered it returns true. I only want it to return true if the match is exact.

//short example
posList = [
    {
        posCode: "43252",
        description: "hi"
    },
    {
        posCode: "HTD632",
        description: "hello"
    }
]

checkPosCodeUnique = () => {
    const re = new RegExp(_.escapeRegExp(this.state.posCode), 'i');
    const isMatch = result => (re.test(result.posCode));
    const list = _.filter(this.state.posList, isMatch);
    if (list.length > 0) {
        error=true;
    }

};

Why do you need to use regex?

 posList = [{ posCode: "43252", description: "hi" }, { posCode: "HTD632", description: "hello" } ] checkPosCodeUnique = (search) => { return posList.some(item => { return item.posCode == search }); }; console.log(checkPosCodeUnique('43252')); console.log(checkPosCodeUnique('HTD632')); console.log(checkPosCodeUnique(123)); 

使用some数组方法:

console.log(posList.some(pos => pos.posCode.toUpperCase() === this.state.posCode.toUpperCase());

For what you describe, you don't need regular expressions, you can simply filter the list:

posList.filter(e => e.posCode === posCode)

See https://codesandbox.io/s/5w95r4zmvl for an implementation of your version and the one using a simple filter.

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