简体   繁体   English

从Javascript中的多维数组中删除元素

[英]Removing element from multidimensional array in Javascript

I am attempting to remove an element from a multidimensional array in javascript, the array is built like this: 我试图从javascript中的多维数组中删除元素,该数组是这样构建的:

selectedClients.push({client: id, package: package_id, transfer: transfer_id});

However there can be multiple clients, in multiple packages in multiple transfers in this array, how could I remove an element from this array using all three identifiers rather than just one? 但是,可以有多个客户端,在此数组中多次传输的多个包中,如何使用所有三个标识符而不是一个标识符从此数组中删除元素?

for example: 例如:

Array[0]
{
client: 1
package: 1
transfer: 1
}
Array[1]
{
client: 2
package: 1
transfer: 1
}
Array[2]
{
client: 1
package: 2
transfer: 2
}

Many Thanks 非常感谢

You can roll your own function, that will take in an object with the exact amount of properties as the ones in your array, and then slice out the object it finds: 您可以滚动自己的函数,该函数将接收具有与数组中的属性数量完全相同的属性的对象,然后slice出它找到的对象:

Say you pass in: 说您通过:

{client: 1, package: 1, transfer: 1}

Lets build! 让我们建立!

//Returns the new array if found, false if nothing
function removeObjectFromArray(objectToRemove, arrayOfObjects) {
    for (var i = 0; i < arrayOfObjects.length; i++) {
        var stringyArrObj       = JSON.stringify(arrayOfObjects[i]),
            stringyRemoveObject = JSON.stringify(objectToRemove);

            if (stringyArrObj === stringyRemoveObject)
                return arrayOfObjects.slice(i, i+1);
    }
return false; 
}

Order of the object IS IMPORTANT, as stringify wont match up if the objects aren't ordered the same way. 对象的顺序很重要,因为如果对象的排序方式不同,则stringify不会匹配。 If that's an issue, you'll have to write a bit of a larger function comparing the keys individually. 如果这是一个问题,则必须编写一些较大的函数,分别比较各个键。

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

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