Javascript JSON stringify No Numeric Index to include in Data

前端 未结 8 1344
天涯浪人
天涯浪人 2021-01-28 10:52

i am trying to pass non numeric index values through JSON but am not getting the data.

var ConditionArray = new Array();
ConditionArray[0] = \"1\";
ConditionArra         


        
相关标签:
8条回答
  • 2021-01-28 11:03

    If you change the first line to

    var ConditionArray = new Object();
    

    you will achieve the desired outcome.

    0 讨论(0)
  • 2021-01-28 11:07

    this is the way how I solved this problem Where tblItemsTypeform is array and arrange is de index of the array :

    let itemsData = [];
       
    
        for(var i = 0; i <= this.tblItemsTypeform.length -1;i++){
            let itemsForms = {
                arrange: i,
                values: this.tblItemsTypeform[i]
            }
            itemsData.push(itemsForms)
        }
    

    And finally use this in a variable to send to api:

    var data = JSON.stringify(itemsData)
    
    0 讨论(0)
  • 2021-01-28 11:14

    JSON structure only recognizes numeric properties of an Array. Anything else is ignored.

    You need an Object structure if you want to mix them.

    var ConditionArray = new Object();
    
    0 讨论(0)
  • 2021-01-28 11:16

    This is because Array does not contain your elements.

    When you do this:

    ConditionArray['module'] = "Test";
    

    You actually add a property to the ConditionArray, not elements. While JSON.stringify converts to string only elements of the ConditionArray. For example:

    var arr = new Array;
    arr['str'] = 'string';
    console.log(arr.length) //outputs 0
    

    You need to use an Object instead of Array

    0 讨论(0)
  • 2021-01-28 11:19

    According to the algorithm for JSON.stringfy (step 4b), only the (numeric) indices of arrays are stringified.

    0 讨论(0)
  • 2021-01-28 11:20

    Since javascript array accepts numeric index only. If you want non numeric index,use Object instead.

    var ConditionArray = {};
    ConditionArray[0] = "1";
    ConditionArray[1] = "2";
    ConditionArray[2] = "3";
    
    ConditionArray['module'] = "Test";
    ConditionArray['table']  = "tab_test";
    var Data = JSON.stringify(ConditionArray);
    

    Here is the working DEMO : http://jsfiddle.net/cUhha/

    0 讨论(0)
提交回复
热议问题