Chen.caijun
Chen.caijun

Reputation: 104

js array to json but some value disappear

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?

Upvotes: 2

Views: 978

Answers (4)

rhopper
rhopper

Reputation: 49

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."

Upvotes: 0

Hong Wang
Hong Wang

Reputation: 113

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.

Upvotes: 0

MoLow
MoLow

Reputation: 3084

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));

Upvotes: 4

Rakesh Varma
Rakesh Varma

Reputation: 161

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.

Upvotes: -1

Related Questions