Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript array push only if value not null

I'm wondering if, and if how the following thing is working:

I have an array defined like the following:

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

What I'm currently doing is pushing the elements into the array, so array.push({number: '1', value: 'one', context: 'someContext'}); and so on, with every array element.

Now this thing is extended: Say there's another key called 'content'. This key has a appropriate value, that is either undefined or a string. Now the question is: If I put the pushing in a function like this:

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

Is there anyway, I can make sure, that the key content is only added to the element, if the content (the function gets as parameter) is not null.

Of course I can modify function like 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 the question is, if there is anyway to do this in the push function. I also thought about something like

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

So it would only be inserted if content is defined, but does this work, it didn't seem like, but maybe theres a mistake in my code.

like image 666
user5638730 Avatar asked Aug 08 '16 19:08

user5638730


1 Answers

With Spread operator for object literals (ECMAScript 2018) it looks super easy:

const myPush = (number, value, context, content) =>
  array.push({
    ...{ number, value, context },
    ...content && { content }
  });
like image 77
dhilt Avatar answered Sep 23 '22 02:09

dhilt