0

Is there a way to create an object in JavaScript only if certain keys are not undefined?

For example, suppose I have some network request that requires a payload:

const payload = {
    key1: 'value1',
    key2: 'value2',
    key3: 'value3'
};

Now, let's suppose that key2 and key3 are optional parameters to a function. If I do not pass those in, and they are left as undefined will the object become:

const payload = {
    key1: 'value1',
};

I'm thinking that maybe using Object.create(...) can help me with this?

Any thoughts? Thanks

User 5842
  • 2,849
  • 7
  • 33
  • 51
  • Yeah, you can use undefined as a placeholder just be sure that you prepare your function to handle it properly (or not accept it at all) – zer00ne Jan 24 '18 at 17:32

3 Answers3

2

Not sure if I get you right, but is something like this that you need?

let payload = {
    key1: 'value1',
    key2: 'value2',
    key3: null,
    key4: undefined
};

let clearObject = function clearObject(obj) {
  let newObj = {};
  
  Object.keys(obj).forEach((key) => {
    if (obj[key]) {
      newObj[key] = obj[key];
    }
  });
  
  return newObj;
};

console.log(clearObject(payload));
DontVoteMeDown
  • 21,122
  • 10
  • 69
  • 105
  • 1
    This is absolutely what I need! Thanks! – User 5842 Jan 24 '18 at 17:30
  • 1
    `obj.hasOwnProperty(key) && obj[key] != null` could be replaced by `if(obj[key])` – PlayMa256 Jan 24 '18 at 17:30
  • @MatheusSilva sure. If the object is not a prototype or the property have to checked in the chain, is ok to do that simple check though. – DontVoteMeDown Jan 24 '18 at 17:33
  • But, an object wont always have/by a prototype due to how it was created and its nature? And just to clarify. The simple comparison i did will only be valid if object !== prototype? I could not understand clearly. Sorry. – PlayMa256 Jan 24 '18 at 17:43
  • @MatheusSilva not always. Run `var a = {}; a.prototype; ` in your console you will see that it has no prototype, but it is still an object. [Check this](https://stackoverflow.com/q/32422867/1267304) to see what I mean. – DontVoteMeDown Jan 24 '18 at 17:47
  • I'm sorry, you right. i was confusing that with the concept of _ _ proto _ _. – PlayMa256 Jan 24 '18 at 17:59
  • @MatheusSilva ikr, it is confusing indeed. – DontVoteMeDown Jan 24 '18 at 18:10
2

You can use array#reduce with Object#key. Iterate through each key and only add those keys whose value isn't null or undefined.

let payload = { key1: 'val1', key2: 'val2', key3: null, key4: undefined },
    result = Object.keys(payload).reduce((r,k) => {
      if(payload[k])
        r[k] = payload[k];
      return r;
    },{});
    
console.log(result);
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
0

When the object is serialized, keys with undefined values will be stripped (relevant since we're talking about network packets). Until it is, a placeholder may exist for the missing keys in the object. This is probably implementation specific and shouldn't be relied on.

var makePacket = function(value1, value2, value3) {
    return { key1: value1, key2: value2, key3: value3 }
}

Calling this with only value1 supplied as in payload = makePacket('test') could give you the result:

payload = {
    key1: 'test',
    key2: undefined,
    key3: undefined
}

If the object is serialized and passed over the network there will be no information about the missing keys and it will be just:

payload = {
    key1: 'test'
}

The difference between the value having a place but being undefined and not existing at all is slightly academic, since your handling code should treat both conditions identically. But be assured that you're not wasting bandwidth on non-existent keys if your serializer is worth using.

GunnerGuyven
  • 541
  • 6
  • 8