Best way to flatten JS object (keys and values) to a single depth array

前端 未结 10 931
梦毁少年i
梦毁少年i 2020-12-05 05:10

I have written this small function to get all keys and values of an object and store them into an array. The object might contain arrays as values...

Object {

10条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-05 05:46

    You can skip the inner loop if you have to push contents of an array to another array. See if this helps --

    function flattenObject(obj) {
    // Returns array with all keys and values of an object
    var array = [];
    $.each(obj, function (key, value) {
        array.push(key);
        if ($.isArray(value)) {
            Array.prototype.push.apply(array, value);
        }
        else {
            array.push(value);
        }
    });
    
    return array;
    }
    var obj = {"key1" : [1,3,3],"key2" : "val", "key3":23};
    var output = flattenObject(obj);
    console.log(output);
    

    Fiddle Link -- https://jsfiddle.net/0wu5z79a/1/

    EDIT : This solution is valid only for your scenario where you know that the nesting is till one level only else you need to have some recursion for deep inner objects.

提交回复
热议问题