简体   繁体   English

通过JavaScript中的引用从JSON树中删除对象

[英]Delete object from json tree by reference in JavaScript

I need to remove an object from an JSON tree. 我需要从JSON树中删除一个对象。 I know a reference to that object. 我知道对该对象的引用。 Is there a nice way to do it via JavaScript or jQuery besides traversing the whole tree? 除了遍历整棵树之外,还有通过JavaScript或jQuery做到这一点的好方法吗?

Example: 例:

    party = {
    "uuid": "4D326531-3C67-4CD2-95F4-D1708CE6C7A8",
    "link": {
        "rel": "self",
        "href": "http://localhost:8080/cim/party/4D326531-3C67-4CD2-95F4-D1708CE6C7A8"
    },
    "type": "PERSON",
    "name": "John Doe",

    "properties": {
        "CONTACT": [            
            {
                "category": "CONTACT",
                "type": "EMAIL",
                "key": "email",
                "value": "john.doe@doe.at",
                "id": "27DDFF6E-5235-46BF-A349-67BEC92D6DAD"
            },
            {
                "category": "CONTACT",
                "type": "PHONE",
                "key": "mobile",
                "value": "+43 999 999990 3999",
                "id": "6FDAA4C6-9340-4F11-9118-F0BC514B0D77"
            }
        ],
        "CLIENT_DATA": [
            {
                "category": "CLIENT_DATA",
                "type": "TYPE",
                "key": "client_type",
                "value": "private",
                "id": "65697515-43A0-4D80-AE90-F13F347A6E68"
            }
        ]
    },
    "links": []
    }

And i have a reference: contact = party.properties.contact[1] . 我有一个参考: contact = party.properties.contact[1] And I want to do something like delete contact . 我想做些delete contact

它仅以一种方式起作用:变量持有引用,但是没有给定特定引用的方式来推断哪些变量持有引用(无需遍历它们并进行比较)。

You may delete it this way. 您可以通过这种方式将其删除。 I just tested it. 我刚刚测试过。

var party = {
    // ...
}

alert(party.properties.CONTACT[0]) // object Object
delete party.properties.CONTACT[0] // true
alert(party.properties.CONTACT[0]) // undefined

Fiddle 小提琴

UPDATE 更新

In the case above party is a direct property of window object 在上述情况下, partywindow对象的直接属性

window.hasOwnProperty('party'); // true

and that's why you can't delete a property by reference. 这就是为什么您不能通过引用删除属性的原因。 Anyhow, behavior of delete operator with host objects is unpredictable. 无论如何,删除操作符与宿主对象的行为是不可预测的。 Though, you may create a scope around the party object and then you'll be allowed to delete it. 不过,您可以围绕party对象创建一个范围,然后将其删除。

var _scope = {};
var _scope.party = {
    // ...
};

var r = _scope.party.properties.CONTACT[0];
window.hasOwnProperty('party'); // false
alert(r) // object Object
delete r // true
alert(r) // undefined

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

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