Skip to content

If is posible add function to conver all object to array? #4

@root9

Description

@root9

I got a lot [object Object],[object Object],[object Object],[object Object] in log on server.

I try some thing to use JSON.stringify but I have Circular reference problem so I write some code like this, maybe you can add to this addon if you like :)

This code maybe need to rewite to work better

var products = [
   {id:102, price:200.3}, 
   {id:3, price:104.5},
   {id:10, price:20},
   [
       {id:102, price:200.3}, 
       {id:3, price:104.5},
       {id:10, price:20},
       [
           {id:102, price:200.3}, 
           {id:3, price:104.5},
           {id:10, price:20},
       ]
   ]
];

function convert2array(obj, properties, deep, maxdeep) {
    ++deep;
    for(var key in obj) {
        if(obj.hasOwnProperty(key) && typeof obj[key] !== 'function') {
            if (deep < maxdeep) { 
                if (obj[key] != null && typeof obj[key]  === "object") {
                    if (obj[key].length > 0) {
                        properties[key] = [];
                        convert2array(obj[key], properties[key], deep, maxdeep);
                    }
                } else if (typeof obj[key]  === "number" || typeof obj[key]  === "string" || typeof obj[key]  === "boolean") {
                    properties.push(key + ': ' + obj[key]);
                } else {
//                    console.log('error: ' + key, obj[key]);
                }
            }
        }
    }

    return properties;
}

var cache = [];
var properties = [];
JSON.stringify(products, function(key, value) {
    if (typeof value === 'object' && value !== null) {
        if (cache.indexOf(value) !== -1) {
            // Circular reference found, discard key
            return;
        }
        if (typeof value  === "object" && value != null) {
            var res = convert2array(value, properties, -1, 4);
            properties.push(key + ': ' + res);
            cache.push(value);
        } else if (typeof value  === "number" || typeof value  === "string") {
            properties.push(key + ': ' + value);
            cache.push(value);
        }
    }
    return value;
});

console.log(properties);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions