2017-10-06 6 views
1

私は以下のようにjsonオブジェクトを持っています。ここでは、 "otherIndustry"エントリとその値を削除するには、以下のコードを使用してください。jsonオブジェクトのキーと値を削除する方法?

var updatedjsonobj = delete myjsonobj['otherIndustry']; 

Jsonオブジェクト固有のキーとその値を削除する方法。 以下は、 "otherIndustry"キーとその値を削除したいと思うjsonオブジェクトの例です。

var myjsonobj = { 
     "employeeid": "160915848", 
     "firstName": "tet", 
     "lastName": "test", 
     "email": "[email protected]", 
     "country": "Brasil", 
     "currentIndustry": "aaaaaaaaaaaaa", 
     "otherIndustry": "aaaaaaaaaaaaa", 
     "currentOrganization": "test", 
     "salary": "1234567" 
    }; 
delete myjsonobj ['otherIndustry']; 
console.log(myjsonobj); 

ここで、ログは「otherIndustry」エントリをオブジェクトから削除せずに同じオブジェクトを印刷します。

+0

[JSONオブジェクトからキーと値のペアを削除する]の可能性のある重複を(https://stackoverflow.com/questions/24770887/remove-key-value-pair-from-json-object) –

+0

あなたのコードはうまくいくはずです、MVCEを作成することができますhttps://stackoverflow.com/help/mcve – gurvinder372

+0

delete myObj.other.key1; [この例に示すように](https://stackoverflow.com/questions/1219630/remove-a-json-attribute/1219633#1219633) –

答えて

6

delete演算子は、オブジェクトpropertyに使用されます。 または

deleteオペレータbooleanを返し、新しいオブジェクトを返していません。一方で

インタプリタがvar updatedjsonobj = delete myjsonobj['otherIndustry'];を実行した後、updatedjsonobj変数はboolean 値を格納します。

Jsonオブジェクト固有のキーとその値を削除するには?

オブジェクトのプロパティからプロパティ名を削除するには、そのプロパティ名を知る必要があります。

delete myjsonobj['otherIndustry']; 

let myjsonobj = { 
 
    "employeeid": "160915848", 
 
    "firstName": "tet", 
 
    "lastName": "test", 
 
    "email": "[email protected]", 
 
    "country": "Brasil", 
 
    "currentIndustry": "aaaaaaaaaaaaa", 
 
    "otherIndustry": "aaaaaaaaaaaaa", 
 
    "currentOrganization": "test", 
 
    "salary": "1234567" 
 
} 
 
delete myjsonobj['otherIndustry']; 
 
console.log(myjsonobj);

あなたはあなたが与えられたオブジェクト自身の列挙可能プロパティの配列を返すObject.keys機能を使用することができます値を知っているときkeyを削除する場合。

let value="test"; 
 
let myjsonobj = { 
 
     "employeeid": "160915848", 
 
     "firstName": "tet", 
 
     "lastName": "test", 
 
     "email": "[email protected]", 
 
     "country": "Brasil", 
 
     "currentIndustry": "aaaaaaaaaaaaa", 
 
     "otherIndustry": "aaaaaaaaaaaaa", 
 
     "currentOrganization": "test", 
 
     "salary": "1234567" 
 
} 
 
Object.keys(myjsonobj).forEach(function(key){ 
 
    if(myjsonobj[key]==value) 
 
    delete myjsonobj[key]; 
 
}); 
 
console.log(myjsonobj);

+0

戻り値にかかわらず、OPのコードに従ってオブジェクトから 'key:value'を削除しますか? – Rajesh

1

それはあなたが探しているもののようにすることができ、これに従ってください:

var obj = { 
 
    Objone: 'one', 
 
    Objtwo: 'two' 
 
}; 
 

 
var key = "Objone"; 
 
delete obj[key]; 
 
console.log(obj); // prints { "objtwo": two}

関連する問題