2016-07-22 63 views
1

我有一个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从我的阵列,它工作正常删除所有重复。虽然它们是唯一的,但当我动态填充数据时(因为有空数据集),总是会留下一个空的对象。我已经尝试_.without函数,如下所述:Remove empty elements from an array in Javascript但它不起作用。这里是我的尝试:

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

数组应该是这样的:

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

我也使用jQuery,如果有与此库的解决方案。

+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

你可以试试这个:

_.filter(myArray, _.isEmpty) 

我以为空手段

var obj = {} 
+0

做'!obj ||'会更安全吗? _.isEmpty(obj)' –

+0

我喜欢更多的陈述式的方法 - 品味我认为 –

+0

我只是想说,这样只会删除空?它会删除null还是undefined? –

1

无需库,只取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 
});