I need a function to check if my obj has a certain property and the value is not undefined to empty.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
var plugin = function() { var data = { options: { size: "" }, source: { url: "v" } }; if (!hasProp(data, 'url')) { return; } console.log('Do something with it'); } plugin(); function hasProp(obj, prop) { for (var p in obj) { if (obj.hasOwnProperty(p)) { if (p === prop && obj[p] !== '' && obj[p] !== undefined && obj[p] !== null) { return obj; } else if (obj[p] instanceof Object && hasProp(obj[p], prop)) { return obj[p]; } } } return null; } |