简体   繁体   中英

Adding array to Json Object outputs array of arrays instead of one array of values (using Jquery)

When adding an array to a json object from two separate select lists i get an array of arrays instead of one array with all the values inside. I'll explain further below:

I get my expected output when I've selected items from select list.选择列表中选择了项目时,我得到了预期的输出。 When that's the case, this code runs:

var jsonObject = {};
jsonObject["someKey"] = $("#selectList1").val();
console.log(jsonObject);

console:

▼ Object {someKey: Array[2]}
    ▼ someKey: Array[2]
        0: "value1"
        1: "value2"
        length: 2
      ► __proto__:Array[0]
    ► __proto__: Object

So the above is correct. But when I select item from separate lists each, this code runs:单独的列表中分别选择项目时,此代码运行:

var jsonObject = {};
jsonObject["keys"] = new Array($("#selectList1").val(), $("#selectList2").val());

console.log(jsonObject);

console:

▼ Object {someKey: Array[2]}
    ▼ someKey: Array[2]
     ▼ 0: Array[1]
         0: "value1"
         length: 1
       ►__proto__: Array[0]
     ▼ 1: Array[1]
         0: "value2"
         length: 1
       ►__proto__: Array[0]
       length: 2
     ► __proto__:Array[0]
    ► __proto__: Object

The above is not my desired output. I've also ran this code, which outputs the same undesired output:

var keys = [];
keys.push($("#selectList1").val());
keys.push($("#selectList2").val());

jsonObject["keys"] = keys;

Any help appreciated, thanks.

Another issue you need to be careful with, is in cases where the query for selected values returns empty, since the array operator ( [] ) or concat will fail:

// Select first array of selected values.
// It can be null so we make it by default an empty array.
var selected = ($("#select-1").val() || [])
  // Then concatenate with second array of values
  .concat($("#select-2").val());

Another elegant way to achieve this, could be querying the selects first, then iterating them for values:

var selected = $("#select-1,#select-2").map(function (i, select) {
    return $(select).val();
  }).toArray();

The later is more readable and you avoid the maybeNotAnArray || [] maybeNotAnArray || [] hack.

Thanks @depperm for your suggestion:

new Array($("#selectList1").val()[0], $("#selectList2").val()[0])

it worked..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM