将JS对象(键和值)展平为单个深度数组的最佳方法 [英] Best way to flatten JS object (keys and values) to a single depth array

查看:37
本文介绍了将JS对象(键和值)展平为单个深度数组的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了这个小函数来获取对象的所有键和值并将它们存储到数组中。该对象可能包含数组作为值...

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...

对象{0:[1,2,3,4]} [0,1,2,3,4] 将所有元素转换为整数

Object { 0: [1,2,3,4] } to [0,1,2,3,4] converting all elements to integers

我想知道是否有一种更快/更清晰的方法:

I wonder whether there is a faster/cleaner way to do so:

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)) {
            $.each(value, function (index, element) {
                array.push(element);
            });
        }
        else {
            array.push(value);
        }
    });

    return array
}


推荐答案

您可以连接所有键和值。 (它没有解决键的类型转换为数字。)

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);

这篇关于将JS对象(键和值)展平为单个深度数组的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆