2016-10-13 1 views
-1

データがあり、空または空のデータをフィルタリングしてフィルタリングする必要があります。Javascriptデータをループして空にするか空にする

この場合、「名前」配列がnullの場合もありますので、そのデータが必要です。

{ 
    "people": [ 
     { 
      "id": "2", 
      "description": "desc here", 
      "names": [ 
       { 

        "name": "name here", 
       }, 
       { 

        "name": "name here", 
       } 
      ], 
      "other": "0" 
     }, 
     { 
      "id": "200", 
      "description": "desc here", 
      "names": null 
      "other": "0" 
     }, 
     { 
      "id": "64", 
      "description": "desc here", 
      "names": [ 
       { 

        "name": "name here", 
       }, 
       { 

        "name": "name here", 
       } 
      ], 
      "other": "1" 
     } 
    ] 
} 

どうすればいいですか?

答えて

1

あなたは、配列を反復処理し、プリミティブが発見されるまで、再帰的なオブジェクトがあります。次に、値を確認して返します。

function copy(object) { 
 
    var o; 
 
    if (Array.isArray(object)) { 
 
     return object.reduce(function (r, a) { 
 
      var v = copy(a); 
 
      v.names !== null && v.names !== '' && r.push(v); 
 
      return r; 
 
     }, []); 
 
    } 
 
    if (object !== null && typeof object === 'object') { 
 
     o = {}; 
 
     Object.keys(object).forEach(function (k) { 
 
      o[k] = copy(object[k]); 
 
     }); 
 
     return o; 
 
    } 
 
    return object; 
 
} 
 

 
var data = { people: [{ id: "2", description: "desc here", names: [{ id: "345", name: "name here", }, { id: "54", name: "name here", foo: "", }], other: "0" }, { id: "2", description: "desc here", names: null, other: "0" }, { id: "64", description: "desc here", names: [{ id: "87", name: "name here", }, { id: "53", name: "name here", }], other: "1" }] }, 
 
    result = copy(data); 
 

 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

+0

これはうまくいきますが、レコード上のnames = nullの場合、新しいリストからレコード全体を削除する必要があります。たとえば.. ..レコードID 200上の私のデータでは、新しい配列 – johnofark

+0

には全く表示されませんでした。 –

-1
new_array=yourObject.people.filter(function(elem){ 
return elem.names!==null && elem.names!=="" 
}); 
+0

これが動作しているようだが、なぜそれが、オブジェクト、オブジェクト、オブジェクト、オブジェクト]としてではなく、元のオブジェクト{人:配列[16]}としてクロムに表示されていますか? – johnofark

+0

私は編集して今すぐ試してください –

+0

フィルタリングの後で変更されているように見えます。残りのコードはエラーになります。フィルタリングした後にもうこのように表示されないのはなぜですか? Object {people:Array [16]} ...今のように表示されます:Object、Object、Object、Object] ...変換? – johnofark

0
var newArray = oldArray.filter(function(v){return v!==''}); 
+0

OPが*なぜ*あなたがこれを推薦しているかを知るために、1行のコードを投稿するのではなく、答えに説明を追加する必要があります。そうでなければ、そうです。 – Mike

関連する問題