如何从Javascript对象中删除对象

时间:2017-05-29 02:31:04

标签: javascript

我想从对象中删除一个对象元素。我尝试了以下但它返回相同而不删除元素。 jsfiddle。我想删除时钟对象。 我该如何删除它?

var position = '{"weather":{"id":"weather","x":0,"y":0,"width":12,"height":9},"google_calendar":{"id":"google_calendar","x":0,"y":10,"width":12,"height":9},"clock":{"id":"clock","x":0,"y":19,"width":3,"height":3},"todo":{"id":"todo","x":3,"y":19,"width":6,"height":4}}';

var name = "clock";
console.log(position);//before delete
delete position.name;
//delete position.name;
console.log(position);//after delete

我想实现这个目标。

{"weather":{"id":"weather","x":0,"y":0,"width":12,"height":9},
"google_calendar{"id":"google_calendar","x":0,"y":10,"width":12,"height":9},
"todo":{"id":"todo","x":3,"y":19,"width":6,"height":4}}

2 个答案:

答案 0 :(得分:3)

首先关闭position是一个字符串,而不是一个对象。

第二关,position.name.name属性进行操作。如果您想对名称在name变量中的属性进行操作,则使用position[name],而不是position.name

因此,如果您从位置声明中删除引号或在其上调用JSON.parse()以使其成为对象,那么就是这样:

var position = {
    "weather": {
        "id": "weather",
        "x": 0,
        "y": 0,
        "width": 12,
        "height": 9
    },
    "google_calendar": {
        "id": "google_calendar",
        "x": 0,
        "y": 10,
        "width": 12,
        "height": 9
    },
    "clock": {
        "id": "clock",
        "x": 0,
        "y": 19,
        "width": 3,
        "height": 3
    },
    "todo": {
        "id": "todo",
        "x": 3,
        "y": 19,
        "width": 6,
        "height": 4
    }
};

然后,你可以这样做:

var name = 'clock';
delete position[name];
console.log(position);

并且,最终将从您的对象中删除clock属性。

答案 1 :(得分:1)

var position = {
    "weather": {
        "id": "weather",
        "x": 0,
        "y": 0,
        "width": 12,
        "height": 9
    },
    "google_calendar": {
        "id": "google_calendar",
        "x": 0,
        "y": 10,
        "width": 12,
        "height": 9
    },
    "clock": {
        "id": "clock",
        "x": 0,
        "y": 19,
        "width": 3,
        "height": 3
    },
    "todo": {
        "id": "todo",
        "x": 3,
        "y": 19,
        "width": 6,
        "height": 4
    }
};

以下声明将完成您的工作。

delete position["clock"]