1

Please see attached screenshot. See pendingApp property of Object. when I am debugging in eclipse then pendingApp show array of object, Which is correct! But when I am JSON.stringify(object) then showing me empty Array. Eclipse Image

Terminal Image

Please let me know reason of this behavior. I think I am not aware with any Java-Script thought/concept ?? :P :)

When I will save this Object into DB then blank array of pendingApp will be stored !!

var pending_app = [];
var new_record = {"pendingApp" : [], "installedApp" :[] };
....SOME CODE+conditions HERE....
 pending_app[appId] = {'action' : action };
 new_record.pendingApp = pending_app;
// create app-config data
 return app_model.create(new_record); //will return promise object
Manish Trivedi
  • 3,481
  • 5
  • 23
  • 29

1 Answers1

1

It's not a weird behaviour but a common mistake of using an Array to store key-value data.

Short Answer : Use a literal Object to store these data


While you can add properties on every objects in Javascript, you cannot iterate over them with the default array mechanisms

for (var i = 0; i < array.length; i++){}
array.forEach();

Simple demonstration :

var array = [];
array["anId"] = 1;
array.length; // 0

array[4294967295] = 1; // Indice >= unsigned 32-bit Max Value
array.length; // 0
array[4294967295]; // 1

So JSON.stringify with the ECMAScript 5 Specification will use the Array mechanism to iterate over all items and will find nothing.

Unlike Objects that you can list properties with

Object.keys(array); // ["anId"]
Hacketo
  • 4,978
  • 4
  • 19
  • 34