I'm trying to remove all undefined field value from the following object. Is there any way to remove all undefined value and get clear object(It means object without any undefined value) without recursive function?
I have tried with lodash something like this
_.transform(obj, function(res, v, k) {
if (v) res[k] = v;
});
and
all I can get succeed object was by doing recursively something like this.
function compactObject(data) {
return Object.keys(data).reduce(function(accumulator, key) {
const isObject = typeof data[key] === 'object';
const value = isObject ? compactObject(data[key]) : data[key];
const isEmptyObject = isObject && !Object.keys(value).length;
if (value === undefined || isEmptyObject) {
return accumulator;
}
return Object.assign(accumulator, {[key]: value});
}, {});
}
However, I would like to make it more simplify. Can any one has good idea of this?
- Problematic object
var fields = {
name: "my name",
note: "my note",
steps: [
{action: 'pick', place: {…}, childrenIds: ['_id1', '_id2']},
{action: 'drop', place: {…}, childrenIds: undefined},
],
email: undefined
}
- Wanted result
var fields = {
name: "my name",
note: "my note",
steps: [
{action: 'pick', place: {…}, childrenIds: ['_id1', '_id2']},
{action: 'drop', place: {…}},
],
}
Thank you in advance!