Reputation: 91
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?
var fields = {
name: "my name",
note: "my note",
steps: [
{action: 'pick', place: {…}, childrenIds: ['_id1', '_id2']},
{action: 'drop', place: {…}, childrenIds: undefined},
],
email: undefined
}
var fields = {
name: "my name",
note: "my note",
steps: [
{action: 'pick', place: {…}, childrenIds: ['_id1', '_id2']},
{action: 'drop', place: {…}},
],
}
Thank you in advance!
Upvotes: 1
Views: 2318
Reputation: 11
you can try this function
const removeUndefined = obj => {
if (Array.isArray(obj)) {
return obj.map(item => removeUndefined(item)).filter(item => Object.keys(item).length > 0);
} else if (typeof obj === 'object' && obj !== null) {
return Object.fromEntries(
Object.entries(obj)
.filter(([, value]) => typeof value !== 'undefined')
.map(([key, value]) => {
if (typeof value === 'object' && value !== null) {
return [key, removeUndefined(value)];
}
return [key, value];
})
);
}
return obj;
};
const result = removeUndefined(fields);
Upvotes: 0
Reputation: 8087
const data = {
name: "my name",
note: "my note",
steps: [
{action: 'pick', place: {}, childrenIds: ['_id1', '_id2']},
{action: 'drop', place: {}, childrenIds: undefined},
],
email: undefined
}
function removeUndefined(o) {
let stack = [o], i;
while(stack.length) {
Object.entries(i=stack.pop()).forEach(([k,v])=>{
if(v===undefined) delete i[k];
if(v instanceof Object) stack.push(v);
})
}
return o;
}
console.log(removeUndefined(data))
Upvotes: 3