0

The following code produces an array based on values of the designated inputs:

 <input value="jan, feb, mar">
 <input value="apr, may, jun">
 <input value="jul, aug, mar">

  ####

  anArray = []
  $("input").each ->
      tv = $(this).val()
      anArray.push(tv)
  console.log anArray

  >>> ["jan, feb, mar", "apr, may, jun", "jul, aug, sep"]

How can I make it to be a set of arrays wrapped in another array?

[ ["jan, feb, mar"], ["apr, may, jun"], ["jul, aug, sep"] ]

I also somewhat managed it to do as a set of objects, but I don't need a key at all. Maybe I can strip this object of key, leaving only value?

    content = $("input")
    object = $.map content, (x) ->
        'key': $(x).val()
    console.log JSON.stringify(object)

    >>> [{"key":"jan, feb, mar"},{"key":"apr, may, jun"},{"key":"jul, aug, mar"}]

In the end I'm going to post this data via JSON to the server, so all what I really need is to meet controller expectations of the data format where each input's value will be grouped together and separated with coma.

2 Answers2

1

Instead of pushing the string, push an array with the strings:

anArray = []
$("input").each ->
    tv = $(this).val()
    anArray.push([tv])
console.log anArray
tcooc
  • 20,629
  • 3
  • 39
  • 57
-1

use the split function:

anArray = []
  $("input").each(function(tv){
      tv = $(this).val()
      anArray.push(tv.split(","))
  })
      
  document.write(JSON.stringify(anArray));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input value="jan, feb, mar">
<input value="apr, may, jun">
<input value="jul, aug, mar">
<br>
MoLow
  • 3,056
  • 2
  • 21
  • 41