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

前端 未结 10 953
梦毁少年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:41

    You could just concat all keys and values. (It does not solve the type casting to number for keys.)

    var object =  { 0: [1, 2, 3, 4] },
        result = Object.keys(object).reduce(function (r, k) {
            return r.concat(k, object[k]);
        }, []);
        
    console.log(result);

提交回复
热议问题