从数组中删除空对象

3

我有一个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的解决方案,我也会用这个库。


1
什么是“empty”?请添加更多数据并指出应该删除哪些内容。 - Nina Scholz
{id:"",text:""} 不是空对象。如果您想要删除其中任何一个出现的对象,请进行过滤。我猜,最终您想要删除任何没有指定 id 的对象。 - A. Wolff
4个回答

7
您可以尝试以下方法:
_.filter(myArray, _.isEmpty)

我理解“empty”意味着空的。

var obj = {}

!obj || _.isEmpty(obj) 更安全吗? - Callum Linington
我更喜欢声明式的方法 - 我认为这是口味问题。 - Oskar Szura
我只是想说,那只会移除空值吗?它也会移除 null 或 undefined 吗? - Callum Linington
显然如此。 - Callum Linington
https://lodash.com/docs#isEmpty - _.isEmpty(undefined) = true, _.isEmpty(null) = true - 我认为这已经足够了。 - Oskar Szura
6
OP是否在寻找反函数?_.filter(myArray, _.isEmpty) 只会保留空对象,_.reject(myArray, _.isEmpty) 会只保留非空对象。 - adelriosantiago

4

尝试使用(ECMA5+):

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

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


1
纯JS比使用underscore.js更好,感谢这个建议!是否还有一个简短的过滤函数可以删除所有重复项,这样我就不必使用underscore.js的函数了吗? - Jandroide
1
我非常感谢你的帮助,但是重复项仍然存在。 - Jandroide

1

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接