0

I am trying to fetch some data using Axios call and modify the data element by removing the matching element using object.splice(index,1)

but at the end result, I get all the elements the splice is not working,

I guess it might be something related to 'async and await' problem but not sure how to solve it.

getBeltDevicesList({ commit, dispatch,rootState}) {
  commit('common/SET_SCROLL_OVER_LOCK_STATE', false, {root: true });
  commit('common/SET_PENDING_STATE', true, { root: true});
  commit('SET_SELECTED_DEVICE_ID', null);
  const queryParams = {
    skip: 0,
    take: rootState.common.itemsOnPage,
    ...rootState.common.searchOptions,
  };
  return DataApiService
    .getDataElements(queryParams)
    .then(data => {
      data.forEach((dataElements, index, object) => {
        //alert(JSON.stringify(data))
        const { vId,typeId} = dataElements;
        if (vId !== null || typeId == 2) {
          // alert(typeId);//splice is not removing the elements 
          object.splice(index, 1);
        }
      });
      commit('SET_LIST', data);
      commit('common/SET_PENDING_STATE', false, {root: true});
      getDataElementsAssigning(data);
      setFormattedBootstrapDate(data);
      const selecteddataElement = rootState.common.pageMode === 'table' || !data.length ? null : data[0];
      dispatch('selectdataElement', selecteddataElement);


    });
}

4
  • You shouldn't delete from the array you're iterating over. You'll skip some elements. Commented Mar 19, 2020 at 2:45
  • thanks for the input what would be the alternative? Commented Mar 19, 2020 at 2:48
  • 1
    use data = data.filter(...) Commented Mar 19, 2020 at 2:48
  • this worked, thanks Commented Mar 19, 2020 at 2:51

1 Answer 1

2

Splice works, but splicing the current element will cause the next element to be skipped in the forEach() loop. Instead, you should use filter() to remove elements from the list.

data = data.filter(({vId,typeId}) => vId === null && typeId != 2);
Sign up to request clarification or add additional context in comments.

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.