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

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

问题描述

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

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

我想知道是否有更快/更干净的方法来做到这一点:

function flattenObject(obj) {//返回包含对象的所有键和值的数组var 数组 = [];$.each(obj, function (key, value) {array.push(key);如果 ($.isArray(value)) {$.each(value, function (index, element) {数组推送(元素);});}别的 {数组推(值);}});返回数组}

解决方案

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

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

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 { 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天全站免登陆