Convert a javascript associative array into json object using stringify and vice versa

后端 未结 5 715
深忆病人
深忆病人 2020-12-14 02:42

I have a javascript associative array like one below

 var my_cars= new Array()
 my_cars[\"cool\"]=\"Mustang\";
 my_cars[\"family\"]=\"Station Wagon\";
 my_ca         


        
5条回答
  •  忘掉有多难
    2020-12-14 03:03

    No,But the user want to use array not json.

    Normal JavaScript arrays are designed to hold data with numeric indexes. You can stuff named keys on to them (and this can be useful when you want to store metadata about an array which holds normal, ordered, numerically indexed data), but that isn't what they are designed for. The JSON array data type cannot have named keys on an array.

    If you want named keys, use an Object, not an Array.

    *source

    var test = [];           // Object
    test[0] = 'test';        //this will be stringified
    

    Now if you want key value pair inside the array

    test[1] = {};          // Array
    test[1]['b']='item';
    var json = JSON.stringify(test);
    

    output

    "["test",{"b":"item"}]"
    

    so you can use an index with array,so alternatively

    var my_cars= [];
    my_cars[0]={};
    my_cars[0]["cool"]="Mustang";
    my_cars[1]={};
    my_cars[1]["family"]="Station Wagon";
    my_cars[2]={};
    my_cars[2]["big"]="SUV";
    console.log(JSON.stringify(my_cars));
    

    Output

    "[{"cool":"Mustang"},{"family":"Station Wagon"},{"big":"SUV"}]"
    

提交回复
热议问题