如何通过指定特定对象的位置来删除数组中的特定对象

how to delete a particular object withiin an array by specifying the its position?

本文关键字:对象 删除 数组 位置 何通过      更新时间:2023-09-26

我有一个如下的对象:在这里,我需要删除数组中名为"cards"的特定对象。

var lists = [
    {
        "cards": [
            {
                "cardDesc": "a",
                "cardTitle": "a",
                "comments": "a"
            },
            {
                "cardDesc": "b",
                "cardTitle": "b",
                "comments": "b"
            }
        ]
    },
    {
        "cards": [
            {
                "cardDesc": "c",
                "cardTitle": "c",
                "comments": "c"
            },
            {
                "cardDesc": "d",
                "cardTitle": "d",
                "comments": "d"
            }
        ]
    }
]

我尝试如下。

$scope.lists[0].cards.pop(x);
$scope.lists[0].cards.slice(x,1);

其中x为卡片中特定对象的位置。

等待您的回复

您需要使用.splice(),而不是.slice()slice返回一个包含所选元素的新数组),splice通过删除所选元素(并返回它们)来修改给定的数组。

var lists = [
    {
        "cards": [
            {
                "cardDesc": "a",
                "cardTitle": "a",
                "comments": "a"
            },
            {
                "cardDesc": "b",
                "cardTitle": "b",
                "comments": "b"
            }
        ]
    },
    {
        "cards": [
            {
                "cardDesc": "c",
                "cardTitle": "c",
                "comments": "c"
            },
            {
                "cardDesc": "d",
                "cardTitle": "d",
                "comments": "d"
            }
        ]
    }
];
var currList = 0;
var x = 1;
lists[currList].cards.splice(x, 1);
console.log(lists);