lt_katana
lt_katana

Reputation: 158

Dynamically fill json object with strings and string arrays

I have the following problem. I am new to json and javascript and i need to dynamically build a json object and feed it with strings. The incoming strings are not sorted so it should be possible to make a string array. I came up with this design but i am getting an error.

 addToDumpObject: function (type, v, dump) {

        if (v instanceof A.entity.Entity) {
            dump.type.push(v.toString());
        } else if (v instanceof jQuery) {
            dump.type.push(v);
        } else if ($.isArray(v)) {
            for (var i in v) {
                A.util.addToDumpObject(type, v[i], dump);
            }
            return;
        } else {
        }
    }

dump is my json object. v could be an instance of entity or an array or an jQuery-object. type is the entity-type and i want to sort the values as the following.

dump{
   "Permission" : [ "PHONE", "SMS" ]
   "String" : [ "MN7", "AT", "DE" ]
};

The error i get is "Uncaught TypeError: Cannot read property 'push' of undefined". And i think its because i used the identifier wrong but i don't know how to fix it if i try dump.[type].push() i get an error for missplaced [].

Upvotes: 0

Views: 145

Answers (1)

SpYk3HH
SpYk3HH

Reputation: 22570

After a complete reread of your situation, I think what you're looking for is something like the following:

addToDumpObject: function (type, v, dump) {
    if (!dump[type]) dump[type] = new Array();
    if (!$.isArray(dump[type])) return;
    else if ($.isArray(v)) for (var i in v) A.util.addToDumpObject(type, v[i], dump);
    else {
        if (v instanceof A.entity.Entity) dump[type].push(v.toString());
        else if (v instanceof jQuery) dump[type].push(v);
        else {
            if (!dump['trash']) dump.trash = new Array(); // simply for collecting other parts / debugging
            dump.trash.push(v);
        }
    }
    return;
}

Upvotes: 1

Related Questions