从数组中移除空对象

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 函数: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。

你可以试试这个:

_.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
});