Home > Enterprise >  react native delete item form array by key
react native delete item form array by key

Time:05-20

i am trying to delete an item from my array by specific key.

this is my code:

Code that generating multi TextInput:

var OtherValuesArr = [];
const OtherValues = () =>{
    for(let i=0; i<otherValuesNumber; i  ){
        var theOutPut = (
          <View style={styles.otherValContainerLoop}>
            <View style={styles.otherValContainerLoopCancel}>
              <TouchablePlatform containerStyle={styles.otherValContainerLoopCancelTouch} onPress={()=>{otherValueRemove(i)}}>
                <Icon name="minus" style={styles.otherValContainerLoopCancelTouchIcon} />
              </TouchablePlatform>
            </View>
            <View style={styles.otherValContainerLoopInput}>
              <TextInput
                  style={[styles.profileFormInputSection_INPUT,!variantValueHandler && {backgroundColor:'#fab8c0'}]}
                  onChangeText={(text) => {setOthersValue(text,i);}}
                  value={othervaluearr[i]}
                  placeholder={t(trans.optionvalue)}
                  placeholderTextColor={placeHolderTextColor}
                  keyboardType="default"
              />
            </View>
        </View>
        );
        OtherValuesArr[i]=theOutPut;
    }
    return OtherValuesArr;
}

Code that handling the inputs (update,remove):

const [othervaluearr,setOtherValueArr] = useState([]);
const setOthersValue = (text,i) =>{
  setOtherValueArr(oldArray => ({...oldArray,[i]:text}));
}
const otherValueRemove = (index) =>{
  console.log(othervaluearr);
}

this is the output of console.log(othervaluearr); :

{"0": "Asdasd", "1": "Asdasdxx"}

i want to remove a specific key, for example: when index = 0, i want to remove "0" and get new array with the following values:

{"1": "Asdasdxx"}

any help please?

CodePudding user response:

try this : var index1 = othervaluearr.indexOf("Asdasd");

othervaluearr.splice(index1, 1);

CodePudding user response:

The problem is that you save an object inside of your array. Your array has one element and it's the object with the values you have.

To solve this you must change the way you save the new data

1st solution

const setOthersValue = (text,i) =>{
  setOtherValueArr(oldArray => [...oldArray,{key: i, value: text}];
}

if you want a stable key. If you want to delete an object, you will search the object with key x and you will delete it.

if you don't want a stable key. just do this simple solution.

2nd solution

const setOthersValue = (text) =>{
  setOtherValueArr(oldArray => [...oldArray, text];
}

const otherValueRemove = (index) =>{
  othervaluearr.splice(index,1);
}

Remember array is with [ ] and object with { }

  • Related