2017-05-29 4 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'は文字列でありオブジェクトではありません。したがって、文字列に '.name'プロパティがないため、' position.name'は 'undefined'です。 – jfriend00

答えて

3

最初にオフpositionは文字列でありオブジェクトではありません。

第2オフオフ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)'への単純な呼び出しが行われます。 – 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"] 
関連する問題