0

for example, I want to add "msg" keys only when msg is not null:

myFunction: function(msg){
  var jsonObj={
    "name" :"abc",
    "time" : 12345,
  };
  if(msg!==undefined){
    jsonObj["msg"]=msg;
  }
  return jsonObj;
}

but I don't want the if statements, is there any syntax to write something like that:

myFunction: function(msg){
  var jsonObj={
    "name" :"abc",
    "time" : 12345,
    msg!==null?["msg":msg]:nothing
  };
  return jsonObj;
}

?

ocomfd
  • 4,010
  • 2
  • 10
  • 19
  • if the intent is to use this for JSON (you call it jsonObj) that you will use JSON.stringify on, to actually end up with JSON, rather than a javascript object - just `msg:msg` because `undefined` values are not converted to JSON – Jaromanda X Apr 11 '18 at 03:21
  • `only when msg is not null` ... your code would only add it if it's not `undefined` rather than not `null` ... `null` !== `undefined` – Jaromanda X Apr 11 '18 at 03:25
  • what is the exact use for the object returned by myFunction – Jaromanda X Apr 11 '18 at 03:27
  • https://stackoverflow.com/questions/11704267/in-javascript-how-to-conditionally-add-a-member-to-an-object/38483660 – epascarello Apr 11 '18 at 04:07

7 Answers7

1

Undefined properties are not copied.

So you can use jquery extend function

var jsonObj = $.extend({}, {
    msg: msg!==null ? msg : undefined,
    // and so on...
});

If msg is null, then msg attribute will not exist in jsonObj

In other way, using ES6 has better solution:

var jsonObj  = {
   ...msg!==null && {msg: msg}
}
Toraaa
  • 145
  • 2
  • 10
0

If you have a default value for msg, then yes, it's possible:

function myFunction(msg){
  var jsonObj={
    name :"abc",
    time : 12345,
    msg: (msg !== null ? msg : "msgDefault"),
  };
  return jsonObj;
}
console.log(myFunction(null));
console.log(myFunction('foo'));

But without a default value, it's impossible - you'd have to resort to an if.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • You could do the trick by setting the default value of msg to undefined instead of msgDefault. – muecas Apr 11 '18 at 03:26
  • It was `null` in the example provided by the OP, so I didn't change that. (sometimes differentiating between `null` and `undefined` is important) – CertainPerformance Apr 11 '18 at 03:31
  • Returning undefined will mean that iterating the object (or possibly converting it to JSON encoded string) will skip the msg key; setting it to null will not. – muecas Apr 11 '18 at 10:19
0

You can delete jsonObj.msg when it is undefined type:

var msg = undefined;
var jsonObj = {
    "name": "abc",
    "time": 12345,
    "msg": msg
};
jsonObj.msg === undefined ? delete jsonObj.msg : false;

jsonObj will add key named "msg" and then delete it depends on the situation.

0

This is the current answer I provide. Just add the field you want and pick the null out when output

function test(msg) {
  var jsonObj = {
    name: 'abc',
    time: 12345,
    msg
  };
  return _.omitBy(jsonObj, _.isNil);
}

console.log(test());
console.log(test(123));
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.5/lodash.min.js"></script>https://stackoverflow.com/posts/49766148/edit#
Rex
  • 137
  • 2
  • 12
0

You could use the fact that Object.assign only "copies" enumerable properties

var msg = null;
var jsonObj = {
    name: 'abc',
    time: 12345
};
Object.assign(jsonObj, Object.create({}, {msg: {value: msg, enumerable: msg !== null}}));
console.log(jsonObj);

However, you call the variable in your code jsonObj - presumably, this object is used to send data to a server using JSON data interchange format? if so, then you can simply do

var msg = null;
var jsonObj={
  "name" :"abc",
  "time" : 12345,
  "msg" : msg !== null ? msg : undefined
};
console.log(JSON.stringify(jsonObj, null, 4));

as JSON.stringify (the function that turns javascript objects into JSON) ignores any property that is undefined

Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
0
myFunction(msg){ 
    var jsonObj=(){ 
        this.name = "abc";
        this.time = 12345;
        msg && this.msg = msg;

        return this;
    };

    return jsonObj;
}

Create object inside closure. AND operation will return value of second operator if first operator is truthy.

On my phone so difficult to test if it executes as written, but that's the conceptual example.

sjensen
  • 41
  • 6
-2

You can shorten your if statement.

if(!obj.msg) obj.msg = null;
Darkrum
  • 1,325
  • 1
  • 10
  • 27
  • Don't Know OP's requirements but this is a pattern I use when designing API's for certain use cases where I know the obj can only be undefined or truthy and then the database does the validation. So yes you can. – Darkrum Apr 11 '18 at 03:27
  • Well breaking down OP's obj it looks like he's building a chat API so this could work. – Darkrum Apr 11 '18 at 03:35
  • Also @JaromandaX what do you mean it won't work when it's `null` or `undefined`? The if statement works as expected. – Darkrum Apr 11 '18 at 03:43
  • Also since it's a msg it is always a string so `0` would never apply unless the user by passes the client but the server would correct it automatically as a int type is not valid string and it would fail thus triggering the if – Darkrum Apr 11 '18 at 03:47
  • Your right it doesn't really answer he's question it's more of a eye opener that you can design a API way more simply if you look at another pattern. – Darkrum Apr 11 '18 at 03:48
  • I don't get why you would assume to know that the value of msg can only be a string or anything else is considered "wrong" ... the first sentence in the body of the question is `I want to add "msg" keys only when msg is not null` – Jaromanda X Apr 11 '18 at 03:51
  • @JaromandaX OP's question is totally irrelevant and belongs in code review not here. – Darkrum Apr 11 '18 at 03:52
  • @JaromandaX Because `msg` implies a string. There's no in between... There's either a body to a msg or not. The fact that OP is putting `null` means he's dealing with some kind of SQL storage but what is the point of storing/communicating something that has no value? – Darkrum Apr 11 '18 at 03:57
  • but `jsonObj` implies the object is going to be made into JSON - so the solution is even simpler as `undefined` properties are ignored in the "stringify" process :p is my inference any less valid than yours :p – Jaromanda X Apr 11 '18 at 03:58
  • @JaromandaX exactly! So again OP needs to realize that what the hell their trying to do can be done differently and more simply! – Darkrum Apr 11 '18 at 03:59