How can we Convert a JS object to an array using jQuery ?

How can we Convert a JS object to an array using jQuery ?

Asked on October 22, 2018 in Javascript.
Add Comment


  • 4 Answer(s)

    The below code can be used to Convert a JS object to an array using jQuery

    var myObj = {
        1: [1, 2, 3],
        2: [4, 5, 6]
    };
    var array = $.map(myObj, function(value, index) {
        return [value];
    });
     
     
    console.log(array);
    

    Output:

    [[1, 2, 3], [4, 5, 6]]
    
    Answered on October 22, 2018.
    Add Comment

    functional approach:

    var obj = {1: 11, 2: 22};
    var arr = Object.keys(obj).map(function (key) { return obj[key]; });
    

    Results in:

    [11, 22]
    

    The same with an ES6 arrow function:

    Object.keys(obj).map(key => obj[key])
    

    With ES7 you will be able to use Object.values instead (more information):

    var arr = Object.values(obj);
    

    Or if you are already using Underscore/Lo-Dash:

    var arr = _.values(obj)
    

     

    Answered on October 22, 2018.
    Add Comment

    We can use the for in but checking if the property is not inerithed

    myObj= {1:[Array-Data], 2:[Array-Data]}
    var arr =[];
    for( var i in myObj ) {
        if (myObj.hasOwnProperty(i)){
            arr.push(myObj);
    }
    }
    

    EDIT – if we want you could also keep the indexes of your object, but we have to check if they are numeric (and we get undefined values for missing indexes:

    function isNumber(n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
    }
     
    myObj= {1:[1,2], 2:[3,4]}
    var arr =[];
    for( var i in myObj ) {
        if (myObj.hasOwnProperty(i)){
            if (isNumber(i)){
                arr = myObj;
            }else{
                arr.push(myObj);
            }
        }
    }
    
    Answered on October 22, 2018.
    Add Comment
    var myObj = {
        1: [1, 2, 3],
        2: [4, 5, 6]
    };
    
    var array = $.map(myObj, function(value, index) {
        return [value];
    });
    
    
    console.log(array);

    Output:

    [[1, 2, 3], [4, 5, 6]]
    Answered on February 14, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.