Javascript array push only if value not null -


i'm wondering if, , if how following thing working:

i have array defined following:

var array = [{number: '1', value: 'one', context: 'somecontext'}, {number: '2', value: 'two', context: 'anothercontext'},...].

what i'm doing pushing elements array, array.push({number: '1', value: 'one', context: 'somecontext'}); , on, every array element.

now thing extended: there's key called 'content'. key has appropriate value, either undefined or string. question is: if put pushing in function this:

push(number, value, context, content){     array.push({        number: number,        value: value,        context: context,        content: content } 

is there anyway, can make sure, key content added element, if content (the function gets parameter) not null.

of course can modify function that:

push(number, value, context, content){     if(!content){         array.push({            number: number,            value: value,            context: context,            content: content    }else{         array.push({            number: number,            value: value,            context: context    } } 

but question is, if there anyway in push function. thought like

   array.push({            number: number,            value: value,            context: context,            content? content: content    } 

so inserted if content defined, work, didn't seem like, maybe theres mistake in code.

any ideas?

if object isn't make code shorter, readable this, create object, add property if there value, , push object array.

push(number, value, context, content) {      var o = {         number  : number,         value   : value,         context : context     }      if (content !== null) o.content = content;      array.push(o); ); 

here's es6 way construct object direcly inside array.push, , filter has null value.

function push(...arg) {     array.push(['number','value','context','content'].reduce((a,b,i)=> {         if (arg[i] !== null) a[b]=arg[i]; return a;     }, {})) } 

Comments