2017-05-12 2 views
1

私は、キー "errMsg"を持つ子を削除したいjsonオブジェクトを持っています。JSONオブジェクト内でループして特定の子を削除します

input JSON : {"info":[{"errorMsg":"Unable to find Vendor ","c2v":"some text"},{"errorMsg":"Unable to find Vendor ","c2v":"Some text"},{"errorMsg":"Unable to find Vendor","c2v":" Some text"},{"id":"1038578481","ven":"DEMOMA","c2v":" Some text"}]} 

結果私は、JSONには "errorMsg"が含まれていない必要があります。

output JSON i want : {"info":[{"id":"1038578481","ven":"DEMOMA","c2v":" Some text"}]} 

私は私のために働いていない

jsonKeyInfo = stringToJson(form.response); 
for(var i in jsonKeyInfo.info){ 
      if(jsonKeyInfo.info[i].errorMsg){ 
       errMsg = jsonKeyInfo.info[i].errorMsg; 
       jsonKeyInfo.info.splice(i,1); 
       err++; 
      // delete jsonKeyInfo.info[i]; 
      } 
     } 

を使用するコード。

答えて

3

それはあなたの配列をフィルタリングし、

var jsonData = {"info":[{"errorMsg":"Unable to find Vendor ","c2v":"some text"},{"errorMsg":"Unable to find Vendor ","c2v":"Some text"},{"errorMsg":"Unable to find Vendor","c2v":" Some text"},{"id":"1038578481","ven":"DEMOMA","c2v":" Some text"}]}; 

var result = jsonData.info.filter(i=>!i.errorMsg) 

console.log(result) 

が戻っ

jsonData.info =結果を使用することをASSINGするには、結果としてあなたに必要なデータをなり、これを試してください。

は:)

+1

非常に良い答えを楽しむあなたのコンソールでこれを試してみてください。 – mohammad

+0

私はエラーが定義されていません、また、このシンボルが何を意味するのかを確認できますか?i.errorMsg –

+0

彼らは矢印関数として知られています。詳細は https://developer.mozilla.org/ja/を参照してください。 docs/Web/JavaScript/Reference/Functions/Arrow_functions –

0

obj = {"info":[ 
 
    {"errorMsg":"Unable to find Vendor ","c2v":"some text"}, 
 
    {"errorMsg":"Unable to find Vendor ","c2v":"Some text"}, 
 
    {"errorMsg":"Unable to find Vendor","c2v":" Some text"}, 
 
    {"id":"1038578481","ven":"DEMOMA","c2v":" Some text"} 
 
    ]} 
 
    
 
    var changed = false; 
 

 
obj.info = obj.info.filter((el)=> !(el.hasOwnProperty("errorMsg") && (changed = true))); 
 
console.log(obj); 
 
console.log("Obj.info changed? " + changed); 
 

 
changed = false; 
 
obj2 = [ 
 
{"id":"1038578481","ven":"DEMOMA","c2v":" Some text"}, 
 
{"id":"1038578481","ven":"DEMOMA","c2v":" Some text"} 
 
]; 
 

 
obj2.filter((el)=> !(el.hasOwnProperty("errorMsg") && (changed = true))); 
 
console.log("Obj2 changed? " + changed);

+0

しかし、私は{info ":" {"id": "1038578481"、 "ven": "DEMOMA"、 "c2v": "Some text"}}}のような出力を得たいとします。 –

+0

結果を 'info'プロパティ(更新されたコード) – barbsan

+0

ありがとうございました –

関連する問題