Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .map into array

I don't know how I would .map into an array. I want to get all values of children but 2 and then put it into an array format.

Here's the code I'm attempting it with:

$("#schoolSupplies").submit(function() {
    var test = $(":input").not("#numOfSupplies, #submitBtn").map(function() {
        return $(this).val();
    })
    .get()
  .join( "\", \"" );

    console.log(test);
});

And this is the output: Billy", "John

I have been working on this for about an hour and I have no idea how.

like image 726
SeanOMik Avatar asked Sep 20 '16 04:09

SeanOMik


People also ask

What is map () in jQuery?

This map() Method in jQuery is used to translate all items in an array or object to new array of items. Syntax: jQuery.map( array/object, callback )

How do you map an array of objects?

The syntax for the map() method is as follows: arr. map(function(element, index, array){ }, this); The callback function() is called on each array element, and the map() method always passes the current element , the index of the current element, and the whole array object to it.

What does .map do in JavaScript?

The map() method in JavaScript creates an array by calling a specific function on each element present in the parent array. It is a non-mutating method. Generally map() method is used to iterate over an array and calling function on every element of array.

What is grep in jQuery?

The grep() method in jQuery finds the array elements that satisfy the given filter function. It does not affect the original array. This method returns the filtered array, i.e., the elements that satisfy the given filter function.


1 Answers

.get() returns an array - so just take out the .join() call; otherwise you would have a string (since that is what .join() returns).

$("#schoolSupplies").submit(function() {
    var arrayOfValues = $(":input").not("#numOfSupplies, #submitBtn").map(function() {
        return $(this).val();
    })
    .get()
  //.join( "\", \"" )
    ;

    console.log('Array.isArray(arrayOfValues): ', Array.isArray(arrayOfValues)?'yes':'no', ' contents of arrayOfValues: ', arrayOfValues);
    return false; //for demonstration purposes, don't submit form normally
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="schoolSupplies">
  Supply Name: <input id="name" type="text" value="Tables" /><br />
  
  Student Name: <input id="studentName" type="text" value="Bobby"/><br />
  # of Supplies: <input id="numOfSupplies" type="number" value="3" /><br />
  <input type="submit" id="submitBtn" />
  </form>
like image 78
Sᴀᴍ Onᴇᴌᴀ Avatar answered Sep 28 '22 19:09

Sᴀᴍ Onᴇᴌᴀ