code_junkie

Remove blank attributes from an Object in Javascript

Nov 12th, 2011
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.75 KB | None | 0 0
  1. var test = {
  2. test1 : null,
  3. test2 : 'somestring',
  4. test3 : 3,
  5. }
  6.  
  7. for (i in test) {
  8. if (test[i] === null || test[i] === undefined) {
  9. // test[i] === undefined is probably not very useful here
  10. delete test[i];
  11. }
  12. }
  13.  
  14. test.test1 === null; // true
  15. test.test1 == null; // true
  16.  
  17. test.test4 === null; // false
  18. test.test4 == null; // true
  19.  
  20. test.test4 === undefined; // true
  21. test.test4 == undefined; // true
  22.  
  23. var obj = { };
  24. obj.theProperty = 1;
  25. delete obj.theProperty;
  26.  
  27. var test = {
  28. a: null,
  29. b: 'hello world',
  30. c: 12345
  31. }
  32.  
  33. var newTest = $.grep(
  34. test,
  35. function(element, index) {
  36. return (test[element] && test[element] != null);
  37. }
  38. );
Add Comment
Please, Sign In to add comment