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?
I think a more efficient way to apply this to nested objects is recursion, as an example:
const mapObject = (obj, f, ctx) => {
ctx = ctx || this;
var result = {};
Object.keys(obj).forEach(function(k) {
if (typeof obj[k] === 'object' && obj[k] !== null) {
result[k] = mapObject(obj[k], f, ctx)
} else {
result[k] = f.call(ctx, obj[k], k, obj);
}
});
return result;
};
console.log(mapObject({
name: "james",
surname: "joyce",
obj: {
objName: "hi"
}
}, (v, k) => v.toUpperCase()))
const filterObject = (obj, f, ctx) => {
ctx = ctx || this;
Object.keys(obj).filter(v => {
if (typeof obj[v] === 'object' && obj[v] !== null) {
filterObject(obj[v], f, ctx)
} else {
return (!f.call(ctx, obj[v], v, obj))
}
}).forEach(v => {
delete obj[v];
})
return obj;
}
console.log(filterObject({
name: "james",
surname: "joyce",
obj : {
name: "objName",
surname: "objSurname",
}
}, (v, k) => k != "name"))