Sulav Timsina
Sulav Timsina

Reputation: 843

How to create a JSON Object's element based on if it is null or not?

     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
}

Upvotes: 0

Views: 138

Answers (4)

Selvio Perez
Selvio Perez

Reputation: 100

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'}

Upvotes: 0

Rajneesh
Rajneesh

Reputation: 5308

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

Upvotes: 0

Rajan
Rajan

Reputation: 1568

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

Upvotes: 1

ABGR
ABGR

Reputation: 5225

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)

Upvotes: 4

Related Questions