1

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!

2
  • 2
    Hi! Please read through the help center, in particular How do I ask a good question? Your best bet here is to do your research, search for related topics on SO and elsewhere, and give it a go. If you get stuck and can't get unstuck after doing more research and searching, post a minimal reproducible example showing your attempt and say specifically where you're stuck. People will be glad to help. Commented Feb 7, 2023 at 10:17
  • @T.J.Crowder Hi! Thanks for pointing me out. You are right. I should have made it with more details not like finger princess. I updated the post with what I tried and the function that even works as I expected but not wanted way. I will more take care for posting for the next time. Thanks again Commented Feb 7, 2023 at 10:27

2 Answers 2

3

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))

Sign up to request clarification or add additional context in comments.

5 Comments

ah! That's exactly what I was looking for. I didn't realize that I can directly delete un-wanted field from the object. Thanks! I will choose yours as answer
I see a potential problem with both the original function by OP and this one, for arrays that contain undefined. OPs function will remove undefined from an array but also change it into a plain object: [ "_id1", undefined, "_id2" ] becomes { "0": "_id1", "2": "_id2" }. This function does not detect undefined in arrays and leaves the array unchanged.
@PeterB this answer does detect undefined in an array, because an array is an object. So if there is an array that looks like [1,undefined,2], the result will be [ 1, <1 empty item>, 2 ]. Iterating over an array with an empty item will cause the empty item to be skipped. The length will not be affected, though. The OP has not specified whether the solution needs to apply to arrays, so I'll amend the answer if required.
Maybe what I see is caused by the Stack Overflow console.log() implementation, perhaps it uses a for-loop for printing. It shows undefined as output if the input is changed so that nested array childrenIds contains an undefined item.
@PeterB ah, that's an interesting observation. I've also just learned that JSON.stringify([1,undefined,2]) will output [1,null,2], which is not what I expected. So both undefined and an empty array element will become null with stringify.
0

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);

2 Comments

Thank you for your answer! That works as well, however, I was looking for the method without recursive :) But Thanks!
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.