1

I have the following JavaScript object:

var items = [
    {
        item1: '',
        item2: 'foo'
    },
    {
        item1: 'bar'
        item2: ''
    }
];

I'd like to remove all key/value pairs where the value is either empty or null. The following doesn't appear to be working as intended:

$.each(items, function(i,v){
    $.each(items[i], function(i2, v2){
        if (v2 === "" || v2 === null){
            delete items[i2];
        }
    });
});
console.log(items);

Console log returns the following error: Uncaught TypeError: Cannot read property 'length' of undefined.

How do I get this work correctly?

0

2 Answers 2

2

For a solution using jQuery .each:

var items = [{
  item1: '',
  item2: 'foo'
}, {
  item1: 'bar',
  item2: ''
}];

$.each(items, function(i, v) {
  $.each(v, function(i2, v2) {
    if (v2 === "" || v2 === null) {
      delete v[i2];
    }
  });
});
console.log(items);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Your delete part was all wrong here:

delete items[i2];

You are trying to delete a property (for example item1) from items not from the item itself.

Sign up to request clarification or add additional context in comments.

Comments

2

With plain Javascript, you could iterate the array and the all keys and check for empty string or null value, then delete if.

var items = [{ item1: '', item2: 'foo' }, { item1: 'bar', item2: '' }];

items.forEach(function (o) {
    Object.keys(o).forEach(function (k) {
        if (o[k] === '' || o[k] === null) {
            delete o[k];
        }
    });
});

console.log(items);

1 Comment

I think I tried to overcomplicate this unnecessarily, your solution is much better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.