转换一个数组对象的数组 [英] Convert an array to an array of objects

查看:151
本文介绍了转换一个数组对象的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么能一个数组转换为JavaScript对象的数组。

How I can convert an array to an array of JavaScript objects.

例如我有一个数组为

data = [
    ["fruits","frozen","fresh","rotten"],
    ["apples",884,494,494],
    ["oranges",4848,494,4949],
    ["kiwi",848,33,33]
]

我想将其转换为名称值对。

I want to convert it to a name value pair.

例如,将得到的集合中的第一个对象将是

For example, first object in the resulting collection would be

 {"fruits": "apple", "frozen": 884, "fresh": 494, "rotten": 494}

等对数据的其余部分。

and so on for rest of the data.

推荐答案

DEMO

使用你提供的数据:

var data = [
    ["fruits","frozen","fresh","rotten"],
    ["apples",884,494,494],
    ["oranges",4848,494,4949],
    ["kiwi",848,33,33]
]

下面的函数将把阵列作为对象的属性键的第一个元素。它将然后在剩余元素环路,并转换成使用这些密钥的目的。最后,它会返回这些新对象的阵列

The following function will treat the first element of the array as the keys for the objects properties. It will then loop over the remaining elements, and convert them into an object using these keys. Finally, it will return an array of these new objects.

function convertToArrayOfObjects(data) {
    var keys = data.shift(),
        i = 0, k = 0,
        obj = null,
        output = [];

    for (i = 0; i < data.length; i++) {
        obj = {};

        for (k = 0; k < keys.length; k++) {
            obj[keys[k]] = data[i][k];
        }

        output.push(obj);
    }

    return output;
}

输出

[
    { fruits: 'apples', fresh: 494, frozen: 884, rotten: 494 },
    { fruits: 'oranges', fresh: 494, frozen: 4848, rotten: 4949 },
    { fruits: 'kiwi', fresh: 33, frozen: 848, rotten: 33 }
]

这篇关于转换一个数组对象的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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