1

オブジェクトが埋め込まれたJavaScript配列があり、データのないすべてのオブジェクトを削除する必要があります。私はすでに正常に動作します私の配列、からすべての重複を削除するunderscore.jsから_.uniqを使用空のオブジェクトを配列から削除する

var myArray = [ {id: "28b", text:"Phill"}, 
       {id: "12c", text:"Peter"}, 
       {id: "43f", text:"Ashley"}, 
       {id: "43f", text:"Ashley"}, 
       {id: "", text:""}, 
       {id: "9a", text:"James"}, 
       {id: "", text:""}, 
       {id: "28b", text:"Phill"} 
       ]; 

:それはこのようになります。それらは一意ではありますが、空のデータセットがあるため、データを動的に記入すると、1つの空のオブジェクトが常に残ります。私は既に_.withoutここで述べたような機能を試しました:Remove empty elements from an array in Javascriptしかしそれは動作しません。

myArray = _.without(myArray, {id:"",text:""}); 

配列は次のようになります:このライブラリで解決策がある場合、私はまた、jQueryのを使用しています

   [ {id: "28b", text:"Phill"}, 
       {id: "12c", text:"Peter"}, 
       {id: "43f", text:"Ashley"}, 
       {id: "9a", text:"James"}, 
       ]; 

ここに私の試みです。

+1

*空*何を意味するのか?いくつかのデータを追加して、何を削除してください。 –

+0

'{id:" "、text:" "}'は空のオブジェクトではありません。この現象を取り除きたい場合は、それをフィルタリングしてください。最後に、あなたが望むのは、 'id'が指定されていないオブジェクトを削除することです。 –

答えて

0

// Code goes here 
 

 
myArray = [{ 
 
    id: "28b", 
 
    text: "Phill" 
 
    }, { 
 
    id: "12c", 
 
    text: "Peter" 
 
    }, { 
 
    id: "43f", 
 
    text: "Ashley" 
 
    }, { 
 
    id: "43f", 
 
    text: "Ashley" 
 
    }, { 
 
    id: "", 
 
    text: "" 
 
    }, { 
 
    id: "9a", 
 
    text: "James" 
 
    }, { 
 
    id: "", 
 
    text: "" 
 
    }, { 
 
    id: "28b", 
 
    text: "Phill" 
 
    } 
 

 
] 
 

 
var result = _.filter(_.uniq(myArray, function(item, key, a) { 
 
    return item.id; 
 
}), function(element) { 
 
    return element.id && element.text 
 
}); 
 
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

+0

は完璧に動作します、ありがとうございます! :) – Jandroide

1

あなたはこれを試すことができます:私は空の手段

var obj = {} 
+0

'!obj || _.isEmpty(obj) ' –

+0

私はより宣言的なアプローチが好きです - 味の問題は私が思うでしょう –

+0

私はそれが空だけを削除するような意味ですか? nullまたは未定義も削除されますか? –

1

ライブラリは必要ないと仮定

_.filter(myArray, _.isEmpty) 

、ちょうどArray#filterし、オブジェクトを取ります。動的フィルタリングでは、すべてのプロパティに対して。

var myArray = [{ id: "28b", text: "Phill" }, { id: "12c", text: "Peter" }, { id: "43f", text: "Ashley" }, { id: "43f", text: "Ashley" }, { id: "", text: "" }, { id: "9a", text: "James" }, { id: "", text: "" }, { id: "28b", text: "Phill" }], 
 
    filtered = myArray.filter(function (a) { 
 
     var temp = Object.keys(a).map(function (k) { return a[k]; }), 
 
      k = temp.join('|'); 
 

 
     if (!this[k] && temp.join('')) { 
 
      this[k] = true; 
 
      return true; 
 
     } 
 
    }, Object.create(null)); 
 

 
console.log(filtered);

+0

純粋なjsはunderscore.jsよりも優れたソリューションです。 underscore.jsを使用する必要がないように、すべての重複を削除するための短いフィルタ関数もありますか? – Jandroide

+0

@Jandroide、編集をご覧ください。 –

+0

本当に助けていただきありがとうございますが、重複はまだ残っています – Jandroide

0

試し(ECMA5の+は):

var myArrayFiltered = myArray.filter((ele) => { 
    return ele.constructor === Object && Object.keys(ele).length > 0 
}); 
関連する問題