0

I am converting JavaScript object to array but in result I am getting one null

here my code

<div id="a"></div>

Object.prototype.toArray = function(){
    var arr = [];
    for (var i in this) {
        arr.push(this[i]);        
    }
    return arr;
} 

var providers = {
            facebooklike: "Facebook Like",
            facebookrecommend : "Facebook Recommend",
            facebooksend : "Facebook Send",
            twittertweet : "Twitter Tweet",
            linkedinshare : "LinkedIn Share",
            linkedinrecommend : "LinkedIn Recommend",
            googleplusplusone : "Google+ +1",
            googleplusshare : "Google+ Share"
        };

var a = document.getElementById("a");
a.innerHTML = JSON.stringify(providers.toArray());

My result is

["Facebook Like","Facebook Recommend","Facebook Send","Twitter Tweet","LinkedIn Share","LinkedIn Recommend","Google+ +1","Google+ Share",null]

Here is fiddle example

0

2 Answers 2

4

Add check for own properties (not inherited from the Object proptotype):

Object.prototype.toArray = function(){
    var arr = [];
    for (var i in this) {
        if(this.hasOwnProperty(i))
            arr.push(this[i]);        
    }
    return arr;
} 
Sign up to request clarification or add additional context in comments.

Comments

3

Add hasOwnProperty check.

for (var i in this) {
    if (this.hasOwnProperty(i)) {
        arr.push(this[i]);
    }        
}

2 Comments

can you tell me why it is getting extra property in for in loop
@GovindKamalaPrakashMalviya And you should know the null comes from the key toArray, and the last element in the result array is a function, which caused null when do JSON.stringify :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.