0
     async homeApi(_source: any, _args: any) {
        const body = {
          door: _args.door,
          window: _args.window
        };
}

I have a typescript code like above where I create a JSON Object called body using door and window arguments. Typically the body should be:

     {
    door: 3,
    window: 4
   }

What I want is if _args.door is empty/blank, the body should be

{window: 4}

It should not be:

{
    door: '',
    window: 4
}
3
  • 4
    Does door: _args.door not already do what you want? If it's undefined, it'll stay undefined. It won't just magically conjure a value out of nowhere. Commented Jun 16, 2020 at 5:29
  • I am sorry. I updated the question. the door element should be removed and shouldn't be blank. Commented Jun 16, 2020 at 5:34
  • 1
    Use a for...in and delete the properties you want according to that condition (btw, undefined is not ""). Commented Jun 16, 2020 at 5:35

4 Answers 4

4

I guess what you want to do is to filter out the fields that are undefined or empty. You could do this:

var data = {
   a: undefined,
   b: "foo"
 }
 
 Object.keys(data).forEach(i=>{
   if(!data[i] && data[i] !==0) delete data[i]
 })
 
 console.log(data)

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

4 Comments

This will delete properties with 0 as well, which seems to be a valid value to OP.
That's a good point. 0 is a fasly value. Let me update that.
Properties with value undefined will already be stripped when encoding to JSON, so the loop is not needed.
@Evert well, I guess null or '' (all falsy except 0) need to be accounted for as well.
1

You can use object assign to get rid of the undefined object. However, for an empty value, you need to check and delete it. You can check below code.

const _args = {
  window: 4
};
const _args1 = {
  door: '',
  window: 4
};
const _args3 = {
  door: 3,
  window: 4
};


homeApi = (_args2) => {
  const bod = { ..._args2};
  if(bod['door'] === ''){
  delete bod['door'];
  }
  console.log(bod);
}

homeApi(_args);
homeApi(_args1);
homeApi(_args3);

Comments

0

One way would be creating object by taking entries and filtering according to your conditions:

const data = {
   a: undefined,
   b: "foo",
   k:0
};

const result = Object.fromEntries(Object.entries(data).filter(([k,v])=>v || v==0));

console.log(result);

Comments

0

You can filter out the fields that are undefined or null as follows:

const data = {
  a: "bar",
  b: undefined,
  c: "faz",
  d: null,
};

const result = Object.keys(data).reduce((obj, key) => {
  if (data[key] !== null && data[key] !== undefined) obj[key] = data[key];
  return obj;
}, {});

console.log(result); // { a: 'bar', c: 'faz'}

Comments

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.