开发者

How to remove an object literals from an array of object literals by object

开发者 https://www.devze.com 2023-04-03 07:09 出处:网络
What is the most general methodology (possibly in javascript) to remove an \"object literal\" from an array of \"objects literal\", I mean how to determi开发者_开发百科ne what the index of the object

What is the most general methodology (possibly in javascript) to remove an "object literal" from an array of "objects literal", I mean how to determi开发者_开发百科ne what the index of the object to be removed is.

The keys are the same, only the values can change.

Lets suppose we have

arrObj = [{k: "a"},{k: "b"},{k: "c"},{k: "d"}]; //{k: "a"}

is just an example of oject literals, but each object could be also more nested like this

{k: "a", {y: {z: "c"}} }

I want to define a function literal which is able to make this stuff:

var removeObjFromArray = function (obj){ ... };    
arrObj.removeObjFromArray({k: "b"}); // {k: "a"},{k: "c"},{k: "d"}


There's probably a much better way of doing whatever it is you're doing. To achieve the solution you want here, you need to iterate over the array and then compare the object. One solution is to use JSON, although you would see a performance hit in older browsers that need the compatibility shim. This is only a viable solution if you don't need to compare functions. Something like this should work:

function removeFromArray(arr, obj) {
    obj = JSON.stringify(obj);
    for (var i=0, max = arr.length; i < max; i++) {
        if (JSON.stringify(arr[i]) === obj)
            arr.splice(i, 1);
    }
}

Working example: http://jsfiddle.net/4JmzV/

Note that, as cdhowie mentions in the comments, order of iteration is a factor with JSON and object properties would need to be defined in the same order. However, without JSON, you'd have to iterate over each object's keys and iterate over the object passed in the argument several times to ensure both objects contain the same keys and same values, making it a more complex task and much slower vs native JSON.

As I said in my first sentence, "There's probably a much better way of doing whatever it is you're doing", and you might be better off taking another look at your approach.


You need to define when two objects are "the same". In your example, the argument to removeObjFromArray is actually a different object (if compared by reference) than the object in the array, since each literal syntax creates a distinct object.

If you know they always have a key named "k", you can compare on that, but I guess you are looking for a more general solution?

You could decide that two objects are the same if they have the same properties with the same values (recursively compared in the case of objects). But it really depends on the uses cases for your program.

0

精彩评论

暂无评论...
验证码 换一张
取 消