2017-05-29 93 views
-3

我想从对象中删除一个对象元素。我已经尝试了以下内容,但是它没有删除元素就返回相同的结果。 jsfiddle。我试图删除时钟对象。 我该如何删除它?如何从Javascript对象中删除对象

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

您显示代码的方式'position'是一个字符串,而不是一个对象。所以,'position.name'是'undefined',因为一个字符串没有'.name'属性。 – jfriend00

回答

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属性。

+0

...并且如果数据*由于某种原因被作为字符串接收,则简单地调用'JSON.parse(position)'etvoilà。 – nnnnnn

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"]