简体   繁体   English

从 JavaScript 的数组中删除 object

[英]Delete object from array in JavaScript

I have an array and I want to delete an object in it.我有一个数组,我想删除其中的 object。 I only have the complete object and I want to delete from the array inside it.我只有完整的 object,我想从里面的数组中删除。

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:我想删除这个 object:

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

How can I do this?我怎样才能做到这一点?

You can use您可以使用

Object.Comments.splice(1, 1);

But you should also give your variable a different name and use let or var.但是你也应该给你的变量一个不同的名字并使用 let 或 var。

You should use a unique id for comments array.您应该为评论数组使用唯一的id

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

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 } ] 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM