1

I have a JSONArrary like this:

myJsonArray = [
    {
        id: '1A',
        name: 'GER'
    },
    {
        id: '2B',
        name: 'BRU',
    },
    {
        id: '3C',
        name: 'ARG'
    }
]

I tried to many ways to remove a complete item. At the moment to remove it, the only value I have is id.

How I can remove (for example) the item with id: '1A' and get as result an array like this:

myJsonArray = [
    {
        id: '2B',
        name: 'BRU',
    },
    {
        id: '3C',
        name: 'ARG'
    }
]
1

2 Answers 2

1

You can use filter method to remove the item from array.

myJsonArray = myJsonArray.filter(x => x.id !== '1A');
Sign up to request clarification or add additional context in comments.

1 Comment

Simple and elegant answer! Thanks!
1

A very simple solution would be:

let index = -1;
for( let i = 0; i < myJsonArray.length; i++ ){
    if( myJsonArray[i].id === searchId ){
       index = i;
    }
}
if(index == -1){
   //however you want to handle it
   console.log("not found");
}
myJsonArray.splice(index, 1);

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.