0

I have an array and I want to delete an object in it. I only have the complete object and I want to delete from the array inside it.

Object = {Comments: [{text: 'hello', x:200, y:100}, 
                     {text: 'hi', x:565, y:454},
                     {text: 'Hola', x:454, y:235}
                    ]
          };

I want to delete this object :

toDelete = {text: 'hi', x:565, y:454}

How can I do this?

zomega
  • 1,538
  • 8
  • 26
Sebastian
  • 21
  • 1
  • 5
  • 1
    Did you make *any* effort at finding the answer yourself? – Scott Hunter Jun 11 '20 at 20:29
  • 1
    Does this answer your question? [Remove Object from Array using JavaScript](https://stackoverflow.com/questions/10024866/remove-object-from-array-using-javascript) – Bronson Jun 11 '20 at 20:30
  • In order to delete something without doing it explicitly, you need to have some type of logic that dictates your reasoning. Why do you want to delete that specific object? Why does it differ from the others and how can you code that into your instructions? – AttemptedMastery Jun 11 '20 at 20:30
  • @ScottHunter yes I made effort , but I don't find myself – Sebastian Jun 11 '20 at 20:32

3 Answers3

0

You can use

Object.Comments.splice(1, 1);

But you should also give your variable a different name and use let or var.

zomega
  • 1,538
  • 8
  • 26
0

You should use a unique id for comments array.

var Object = {
    Comments: [{
            id: 1,
            text: 'hello',
            x: 200,
            y: 100
        },
        {
            id: 2,
            text: 'hi',
            x: 565,
            y: 454
        },
        {
            id: 3,
            text: 'Hola',
            x: 454,
            y: 235
        }
    ]
};

const {
    Comments
} = Object;

function deleteComment = (itemArray, id) => {
    return itemArray.filter(itm => {
        return itm.id !== id
    })
}


const filterdArray = deleteComment(Comments, passYourTargetId);
// in this filterdArray you get without that item you want to remove and it work with immutable way
MD. Sani Mia
  • 272
  • 1
  • 7
0

You can use filter to remove an item from an array:


const myArray = [
  { text: 'one', digit: 1 },
  { text: 'two', digit: 2 },
  { text: 'three', digit: 3 }
];

const filteredArray = myArray.filter(item => {
  return item.text !== 'two' && item.digit !== 2
});

console.log(filteredArray); // [ { text: 'one', digit: 1 }, { text: 'three', digit: 3 } ] 

Tibebes. M
  • 6,940
  • 5
  • 15
  • 36
RobotEyes
  • 4,929
  • 6
  • 42
  • 57