Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
root9 opened this issue Sep 21, 2013 · 0 comments
Open

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

root9 opened this issue Sep 21, 2013 · 0 comments

Comments

@root9
Copy link

root9 commented Sep 21, 2013

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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant