从数组中删除空对象 [英] Remove empty Objects from Array

查看:405
本文介绍了从数组中删除空对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JavaScript数组,其中填充了对象,并且想要删除没有数据的每个对象.可能看起来像这样:

I have a JavaScript-array with objects filled in and want to remove every object with no data. It might look like this:

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中的数组,但是它不起作用.这是我的尝试:

I already use _.uniq from underscore.js to remove all duplicates from my array, which works fine. Though they are unique, one empty Object is always left when I dynamically fill in data (because there are empty datasets). I already tried the _.without function as mentioned here: Remove empty elements from an array in Javascript but it doesn't work. Here is my attempt:

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

该数组应如下所示:

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

如果该库有解决方案,我也使用jQuery.

I am also using jQuery if there is a solution with this library.

推荐答案

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

这篇关于从数组中删除空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆