/** * Andrew Mead * * object.reduce(objToMatch) * * A simple way to return specific properties from an object * * EXAMPLE * var obj = { * name: "andrew", * address: { * street: "Corinthian Ave", * city: "Philadelphia" * }; * * var objToMatch = { * name: true, * address: { * city: true * } * }; * * (obj.reduce(objToMatch) == { * name: "andrew", * address: { * city: "Philadelphia" * } * }) * * Supported Attributes Values * - true: include attribute. If it is an object, include all chiildren * - false: exclude attribute and children * - undefined: exclude attribute and children * */ Object.prototype.reduce = function (map) { var obj = this; var newObj = {}; // get all properties and nested properties of map that are true var props = []; function addProps (path) { // get all the properties at this level // path is 'obj' if it is the objects root // path is 'obj.level1.level2' if not the root of object var level = eval(path); if (typeof level == 'object') { for (attr in level) { if (level.hasOwnProperty(attr) === true) { // see if this is a value or nested object addProps(path + '.' + attr); } } } else if (eval(level) === false) { // ignore that shit! } else { var tempPath = path.split('.'); tempPath[0] = 'obj'; props.push(tempPath.join('.')); } } addProps('map'); // the thing we found in map // var i; // sift through props and copy them from obj into newObj for (i = 0; i < props.length; i += 1) { var prop = props[i], newProp = ''; var temp = prop.split('.'); temp[0] = 'newObj'; newProp = temp.join('.'); // check that potentially nested object exist var newPropArray = newProp.split('.'); // loop though for (var j = 1; j < newPropArray.length; j += 1) { var toCreate = newPropArray.slice(0, j).join('.'); if (toCreate.indexOf('.') === -1) { } else { if (typeof eval(toCreate) == 'undefined') { eval(toCreate + '={};'); } } } eval(newProp + '=' + prop); } return newObj };