0

I'd like to make an array how this:

var varOne, varTwo, varThree; // (If vars are == null don't insert on array)
var array = [];
array = [
    {"ONE": varOne},
    {"TWO": varTwo},
    {"THREE": varThree}
    ]; 

The inputs to the array I'd like to do only when varOne, varTwo and varThree are other than null

Best regards

3
  • You want to filter the variables if there are not null? Commented Sep 25, 2014 at 8:50
  • What is the question here? What are you trying to achieve? Commented Sep 25, 2014 at 8:52
  • I want to filter when the variables are null, for example, if varOne==null the array will be [{"TWO": varTwo},{"THREE": varThree}] Commented Sep 25, 2014 at 8:52

2 Answers 2

1

Looks pretty natural to use if blocks for this:

if (varOne !== null) {
    array.push({ONE: varOne});
}

and so on.

Sign up to request clarification or add additional context in comments.

Comments

0

Just to add to dfsqs answer, you could create a function whichtakes any number of arguments and uses an iterator to perform a null check on each one. (ie use the arguments object - see JavaScript variable number of arguments to function) This code will give you an array of [{"1":"x"},{"2":"z"}]

function foo() {
 var array = [];
 var counter = 0;
 for (var i = 0; i < arguments.length; i++) {
    if (arguments[i]){ 
       counter++;
       var map = {};
       map[counter] = arguments[i]
       array.push(map);
        //document.write(i + " " + arguments[i] + " ");
    }   
 }
 return array;
}

var varOne="x"; 
var varTwo=null; 
var varThree="z"; // (If vars are == null don't insert on array)

var array = foo(varOne,varTwo,varThree); //could be as many variables as you like
//document.write(JSON.stringify(array));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.