从Array中删除空对象

我有一个填充了对象的JavaScript数组,并希望删除没有数据的每个对象。 它可能看起来像这样:

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"} ]; 

我已经使用_.uniq来自underscore.js的_.uniq来删除我的数组中的所有重复项,这很正常。 虽然它们是唯一的,但是当我动态填充数据时,总是会留下一个空对象(因为有空数据集)。 我已经尝试过这里提到的_.without函数: 在Javascript中从数组中删除空元素但它不起作用。 这是我的尝试:

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

该数组应如下所示:

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

如果有这个库的解决方案,我也在使用jQuery。

 // 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) 
  

你可以试试这个:

 _.filter(myArray, _.isEmpty) 

我假设空手段

 var obj = {} 

不需要库,只需要使用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); 

尝试(ECMA5 +):

 var myArrayFiltered = myArray.filter((ele) => { return ele.constructor === Object && Object.keys(ele).length > 0 });