2
window.onload = function() {
  var arr = new Array;
  var jsonObj = {
    "123": "234"
  };
  arr['v'] = "234";
  arr[0] = jsonObj;
  arr[1] = jsonObj;
  console.log(JSON.stringify(arr));
}

The above code result is :

[{"123":"234"},{"123":"234"}]

I don't know why the arr['v'] disappeared?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Chen.caijun
  • 104
  • 2
  • 11
  • misuse of an array. it should be an object for the purpose. – Nina Scholz Sep 04 '16 at 13:55
  • Possible duplicate of [Convert a javascript associative array into json object using stringify and vice versa](http://stackoverflow.com/questions/7089118/convert-a-javascript-associative-array-into-json-object-using-stringify-and-vice) – Nehal J Wani Sep 04 '16 at 13:59

4 Answers4

4

Object and Array are not parsed to JSON the same way.

an Array will only include the numeric keys, and an Object will include all of its keys:

var Arr = [], Obj ={};

Arr[0] = Obj[0] = 'a';
Arr[1] = Obj[2] = 'b';
Arr['key'] = Obj['key'] = 'c';

console.log(JSON.stringify(Arr));
console.log(JSON.stringify(Obj));

so in your case, you could simply use an Onject instead of an array:

var arr = new Object;
var jsonObj = {"123":"234"};
arr['v'] = "234";
arr[0] = jsonObj;
arr[1] = jsonObj;
console.log(JSON.stringify(arr));
MoLow
  • 3,056
  • 2
  • 21
  • 41
0

Actually, JSON.stringify will ignore non-numeric keys in Array during the Array JSON serialization. From the latest ECMA Spec, in section "24.3.2.4 Runtime Semantics: SerializeJSONArray ( value )", we know JSON.stringify only utilizes length of Array and related numeric keys to do the serialization, and Array length will not be affected by its non-numeric keys. So it is now clear why 'v' (non-numeric keys) disappear in your final result.

Hong Wang
  • 93
  • 2
  • 11
0

You can't use a string as an array index, unless it is a string representation of an integer.

Therefore, arr['v'] has no meaning.

This stackoverflow question goes into more detail, but the relevant part:

Yes, technically array-indexes are strings, but as Flanagan elegantly put it in his 'Definitive guide':

"It is helpful to clearly distinguish an array index from an object property name. All indexes are property names, but only property names that are integers between 0 and 232-1 are indexes."

Community
  • 1
  • 1
rhopper
  • 49
  • 8
-1

In JavaScript, basically two types of array, Standard array and associative array. Standard array is defined by [], so 0 based type indexes. And in associative array is defined by {}, in this case you can define string as keys. So in your code you are using both is single array, that's not acceptable. So define the another array if you want strings keys.

Rakesh Varma
  • 151
  • 1
  • 2
  • 14