结合两个数组形成一个JavaScript对象 [英] Combining two arrays to form a javascript object

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

问题描述

我有两个数组:

var columns = ["Date", "Number", "Size", "Location", "Age"];

var rows = [["2001", "5", "Big", "Sydney", "25"],["2005", "2", "Med", "Melbourne", "50"],["2012", "20", "Huge", "Brisbane", "80"]];

我试图将它们组合成一个JavaScript对象的行阵列中的每个项目。在那之后,我想每个对象推到一个新的数组。

I'm trying to combine them into a javascript object for each item in the rows array. After that, I want to push each object into a new array.

我爱:

var newarray = [];

//'thing' should be the same structure for each row item
var thing = {
   "Date" : "2001",
   "Number" : "5",
   "Size":"Big",
   "Location":"Sydney",
   "Age":"25"
}

newarray.push(thing);

我能做到这一点,当我知道列的名字,但我需要能够将数据存储在这种方式,当列名称未知 - 基于列数组的索引,即

I can do this when I know the names of the columns, but I need to be able to store the data in this way when the column name is unknown - i.e. based on the indexes of the columns array.

我试着像这样前:

       for(var y = 0; y < rows.length; y++){

            for(var i = 0; i < columns.length; i++){
                 thing[columns[i]] = rows[i][i];
           }
              newarray.push(thing)
       }

在code只存储中的第一项以上连连(根据rows.length)。

The code above only stored the first item again and again (according to rows.length).

我不明白如何将列名与行结合起来,创造对象的数组。该行包含阵列事实是特别令人困惑。

I don't understand how to combine the column names with the rows to create an array of objects. The fact that 'rows' contains arrays is especially confusing..

推荐答案

在外部循环的每次迭代的开始创建一个新的的事情对象。如果你不这样做,每次你说的事情[列[I]] 你将覆盖同一个对象的属性,当你推入 newarray 什么你会最终是一个充满引用数组的同一个对象的。另外,内循环可确保您得到正确的指标(目前你有 [I] [I] 而不是 [Y] [我]

Create a new thing object at the beginning of each iteration of the outer loop. If you don't do so, each time you say thing[columns[i]] you'll be overwriting the properties of the same object, and when you push it into newarray what you'll end up with is an array full of references to the same object. Also, inside the loop be sure you get the indexes right (you've currently got [i][i] instead of [y][i]):

var newarray = [],
    thing;

for(var y = 0; y < rows.length; y++){
    thing = {};
    for(var i = 0; i < columns.length; i++){
        thing[columns[i]] = rows[y][i];
    }
    newarray.push(thing)
}

是行包含数组是特别令人困惑的事实。

有关示例数据 rows.length 将是3,和行[0] 是数组:

For your sample data rows.length will be 3, and rows[0] is the array:

["2001", "5", "Big", "Sydney", "25"]

行[0] [3] 是悉尼。

使用,作为一个例子,你应该能够看到行[Y] [I] 会给你的 y各值 I ...

Using that as an example you should be able to see what rows[y][i] will give you for each value of y and i...

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

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