1

How to remove an object by index from array of objects in array of objects.

I want to remove the first object from the array with a variable value in the object id "A1"

let data =
[ 
  { id: 'A1',
    value:  [ { uri: 'B45AA03A05B7.jpg', type: 'image/jpeg' },
              { uri: '30A42FBC1146.jpg', type: 'image/jpeg' } ] 
  },
  { id: 'A2',
    value:  [ { uri: 'G455HFG2FF56.jpg', type: 'image/jpeg' },
              { uri: 'TY6DFG7RTGF.jpg', type: 'image/jpeg' } ] 
  }
]

required output

let data =
[ 
  { id: 'A1',
    value:  [ { uri: '30A42FBC1146.jpg', type: 'image/jpeg' } ] 
  },
  { id: 'A2',
    value:  [ { uri: 'G455HFG2FF56.jpg', type: 'image/jpeg' },
              { uri: 'TY6DFG7RTGF.jpg', type: 'image/jpeg' } ] 
  }
]

i tried this

const array1 = data.filter((item) => item.id == deleteId)

   if (delIndex > -1) {
     array1[0].value.splice(delIndex, 1);
   }
4
  • yes, that's how you'd do it ... if delIndex is 0, it deletes the first, and 1 deletes the second ... how is delIndex set? Commented Jul 2, 2021 at 8:13
  • This should work if deleteId and delIndex are correctly set. Commented Jul 2, 2021 at 8:15
  • Why is this question tagged as react-native? Are you using data or array1 in a state? If so you probably don't want to use splice() since a state should not be mutated, only re-assigned. Commented Jul 2, 2021 at 8:20
  • sorry, but what is even the question? What is the problem? "I tried this ..." OK, code looks good to me -> question solved? Otherwise please explain what problem you have. What is not working? And maybe how is it not working? How does the result that you get differ from the result you expect. Commented Jul 2, 2021 at 8:23

3 Answers 3

2

You could find the object and delte the first object of value.

let data = [{ id: 'A1', value: [{ uri: 'B45AA03A05B7.jpg', type: 'image/jpeg' }, { uri: '30A42FBC1146.jpg', type: 'image/jpeg' }] }, { id: 'A2', value: [{ uri: 'G455HFG2FF56.jpg', type: 'image/jpeg' }, { uri: 'TY6DFG7RTGF.jpg', type: 'image/jpeg' }] }],
    deleteId = 'A1',
    object = data.find(({ id }) => id == deleteId);

if (object) object.value.splice(0, 1);

console.log(data);

Sign up to request clarification or add additional context in comments.

Comments

1

You can try something like this:

data.reduce((prev,curr) => {
  if (curr.id === "A1") {
    curr.value.shift()
  }
  return [...prev, curr]
}, [])

Comments

0

Try this, It works!

// ?. this is optional chaining for javascript operator

data.find(item => item.id === 'A1')?.value.shift();

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.