Array of Array, JSON.stringify() giving empty array instead of entire object

后端 未结 4 1183
后悔当初
后悔当初 2020-12-17 02:26

Here\'s my array (from Chrome console):

\"array

Here\'s the pertinent part of code:

4条回答
  •  盖世英雄少女心
    2020-12-17 03:04

    In javascript arrays have indexes that are numeric keys. JSON.stringify assumes that an array have only properties which are numbers.

    You want to use an object, as what you have is not an array, but resembles a dictionary.

    Here is an example I made: http://jsfiddle.net/developerwithacaffeineproblem/pmxt8bwf/2/

    object = Object()
    object["age"] = 1
    object["cars"] = 2
    object["girlfriends"] = 3
    
    JSON.stringify(object)
    

    Results in:
    "{"age":1,"cars":2,"girlfriends":3}"

    Afterwards when you parse the data if you want to iterate it you can use a piece of code similiar to this:

    for (var key in yourobject) {
      if (yourobject.hasOwnProperty(key)) {
         console.log(key, yourobject[key]);
      }
    }
    

提交回复
热议问题