I wrote these two functions that maps and filter flat objects properties:
var mapObject = (obj, f, ctx) => {
ctx = ctx || this;
var result = {};
Object.keys(obj).forEach(function(k) {
result[k] = f.call(ctx, obj[k], k, obj);
});
return result;
};
var filterObject = (obj, f, ctx) => {
ctx = ctx || this;
Object.keys(obj).filter(v => {
return (!f.call(ctx, obj[v], v, obj))
}).forEach(v => {
delete obj[v];
})
return obj;
}
These two functions can map "flat" properties (i.e. non nested objects) of and object or can filter non nested object properties in this way:
var mapObject = (obj, f, ctx) => {
ctx = ctx || this;
var result = {};
Object.keys(obj).forEach(function(k) {
result[k] = f.call(ctx, obj[k], k, obj);
});
return result;
};
var filterObject = (obj, f, ctx) => {
ctx = ctx || this;
Object.keys(obj).filter(v => {
return (!f.call(ctx, obj[v], v, obj))
}).forEach(v => {
delete obj[v];
})
return obj;
}
console.log(mapObject({
name: "james",
surname: "joyce"
}, (v, k) => v.toUpperCase()))
console.log(filterObject({
name: "james",
surname: "joyce"
}, (v, k) => k != "name"))
console.log(mapObject(filterObject({
name: "james",
surname: "joyce"
}, (v, k) => k != "name"), (v, k) => v.toUpperCase()))
How to efficiently apply this to nested objects i.e. objects having objects properties?