1

I want to delete an object from an array of objects into another array in React, but I am a bit confused, so far I can push an object into the array. But abit confused how to delete it by index.

data

const addValues = [
  {
    "name": "New 1",
    "Value": [98,15,7,8]
  }, 
  {
    "name": "New 2",
    "Value": [7,18,9,40]
  },
  {
    "name": "New 3",
    "Value": [0,19,50,98]
  },
  {
    "name": "New 4",
    "Value": [56,89,34,20]
  },
]

const [value, setValue] = useState([]);

const handlePush = () => {
  setValue(oldArray => [...oldArray, newValue]);
};

 <div>{addValues?.map((inside, index) => {
    return (
      <React.Fragment key={index}>
         <p>{inside.name} <button onClick={() => setTags(oldArray => [...oldArray, addValue[index]])}>Add</button></p>
       </React.Fragment>
    )
  })}</div>
1
  • 2
    Can you show your code for deleting? Commented Nov 8, 2021 at 17:34

3 Answers 3

6

If you want a subset of an immutable array, that's called a filter operation. And to remove an item by index, then you simply want filtering logic to filter out one specific index.

For example:

const handleRemove = (removeIndex) => {
  setValue(oldArray => {
    return oldArray.filter((value, i) => i !== removeIndex)
  })
}
Sign up to request clarification or add additional context in comments.

1 Comment

This was also the answer i was writing ^^
2

Can use filter to generated a new array without position you wanted to cut

Like this:

const filteredArray = items.filter((item, index) => index !== value);

Comments

0

You can use the splice function to to this, given an array index:

const handleDelete = (arrayIndex) => {
  setValue(oldArray => oldArray.splice(arrayIndex,1));
};

Inside code

const addValues = [
  {
    "name": "New 1",
    "Value": [98,15,7,8]
  }, 
  {
    "name": "New 2",
    "Value": [7,18,9,40]
  },
  {
    "name": "New 3",
    "Value": [0,19,50,98]
  },
  {
    "name": "New 4",
    "Value": [56,89,34,20]
  },
]

const [value, setValue] = useState([]);

const handlePush = () => {
  setValue(oldArray => [...oldArray, newValue]);
};

const handleDelete = (arrayIndex) => {
  setValue(oldArray => oldArray.splice(arrayIndex,1));
};

 <div>{addValues?.map((inside, index) => {
    return (
      <React.Fragment key={index}>
         <p>{inside.name} <button onClick={() => setTags(oldArray => [...oldArray, addValue[index]])}>Add</button></p>
       </React.Fragment>
    )
  })}</div>


Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.