Remove empty Objects from Array

大憨熊 提交于 2020-01-11 10:51:11

问题


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"}
              ];

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:""});

The array should look like this:

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

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


回答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>



回答2:


You can try this:

_.filter(myArray, _.isEmpty)

I assume empty means

var obj = {}



回答3:


No need for a library, just take Array#filter and an object. With dynamic filtering, for all properties.

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);



回答4:


try (ECMA5+):

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


来源:https://stackoverflow.com/questions/38521648/remove-empty-objects-from-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!