Remove empty Objects from Array

后端 未结 4 1610
礼貌的吻别
礼貌的吻别 2021-01-21 16:35

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:\"Phil         


        
相关标签:
4条回答
  • 2021-01-21 17:05

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

    0 讨论(0)
  • 2021-01-21 17:06

    try (ECMA5+):

    var myArrayFiltered = myArray.filter((ele) => {
      return ele.constructor === Object && Object.keys(ele).length > 0
    });
    
    0 讨论(0)
  • 2021-01-21 17:19

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

    0 讨论(0)
  • 2021-01-21 17:28

    You can try this:

    _.filter(myArray, _.isEmpty)
    

    I assume empty means

    var obj = {}
    
    0 讨论(0)
提交回复
热议问题