Home > Blockchain >  How to search through an array of Object with varying search parameters in VueJs3?
How to search through an array of Object with varying search parameters in VueJs3?

Time:07-06

I have a search function, which looks at Objects and displays results, based on if there is a match with the chosen search parameter (ID, NAME).

This works fine via searching with an ID, but when I attempt to use name, it returns undefined, and I can't see why ID can be succesfully returned, but name cannot.

Store:

export const useCaseFileStore = defineStore('caseFile', {
    state: () => ({
        matchingCaseFiles: [],
        searchMethod: null,
        caseFiles: [{
            name: 'John Cramer',
            id: 1111,
            title: 'test Files'
        },
        {
            name: 'John Cramer',
            id: 11212,
            title: 'test fileTwo'
        }
        ],
        activeCaseFile: [{
            name: null,
            id: null,
            title: null
        },],
    }),
  actions: {
    searchByCf(searchQuery) {
        this.activeCaseFile = searchQuery;
    },

getters: { 
    activeCaseFiles: (state) => {
        return state.caseFiles.find(cf => cf.id === state.activeCaseFile);
    },
},

Search Component:

<input
   placeholder="Type here to start a search and press ENTER"
   
   v-model="searchInput"
  />
  
 const searchInput = ref(0);

 watch(searchInput, async (newVal) => {
  store.searchByCf(newVal);
});

CodePudding user response:

activeCaseFile Shouldn't be an array it should be an empty string on initial load, as it updates with the input value.

 activeCaseFile: ''

Also, you need to use filter method not find method to return all items that match the input value.

If you want the search without casesensitive

activeCaseFiles: (state) => {
    const inputValueAsLowerCase = state.activeCaseFile.toLowerCase()
    return state.caseFiles.find(cf => 
 inputValueAsLowerCase.includes(cf.id) || 
 inputValueAsLowerCase.includes(cf.name.toLowerCase() ||
 inputValueAsLowerCase.includes(cf.title.toLowerCase())));
},

If not just remove toLowerCase() method.

  • Related