繁体   English   中英

从数组中删除空对象

[英]Remove empty Objects from 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"}
              ];

我已经在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。

您可以尝试以下方法:

_.filter(myArray, _.isEmpty)

我认为是空的意思

var obj = {}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM