不能将多维数组重组为一个?

时间:2016-02-23 07:01:10

标签: javascript arrays multidimensional-array

我有标头field数组和用户info数组,所以我需要重新排列新的一个多数组。我想将field数组值设置为{{1}移动new key索引0到名称下,1到年龄,2到性别......

info

但是,我只是得到数组就像上面的console.log

如何像这样输出,我不知道

var customer = [];

var field = ["Name","Age","Gender"];

var info = [
 ["David","32","Male"],
 ["John","35","Male"],
 ["Enna","28","Female"],
 ["Watson","22","Female"]
 ];

info.map(function(each,i){
each.map(function(data,index){
  customer[field[index]] = data;
});
});

console.log(customer);//[Name: "Watson", Age: "22", Gender: "Female"]

3 个答案:

答案 0 :(得分:1)

以下是您正在寻找的答案

    var customer = {};

var field = ["Name","Age","Gender"];

var info = [
 ["David","32","Male"],
 ["John","35","Male"],
 ["Enna","28","Female"],
 ["Watson","22","Female"]
 ];

info.map(function(each,i){
    each.map(function(data,index){
        if (!customer[field[index]])customer[field[index]] = []
        customer[field[index]].push(data);
    });
});
console.log(customer);

//sample output  
{ Name: [ 'David', 'John', 'Enna', 'Watson' ],
  Age: [ '32', '35', '28', '22' ],
  Gender: [ 'Male', 'Male', 'Female', 'Female' ] } 

答案 1 :(得分:1)

我建议使用每个数组Array.prototype.forEach(),并将结果元素作为属性使用。

  • customer需要成为一个对象。 (它也适用于数组,但它具有误导性,而数组是对象的特殊形式。)
  • customer包含来自field的数据
  • 的属性
  • 如果没有设置
  • ,内部循环会创建peoperties
  • 将值推送到相应的数组

var field = ["Name", "Age", "Gender"],
    info = [
         ["David", "32", "Male"],
         ["John", "35", "Male"],
         ["Enna", "28", "Female"],
         ["Watson", "22", "Female"]
    ],
    customer = function (data, keys) {
        var r = {};
        data.forEach(function (a) {
            keys.forEach(function (k, i) {
                r[k] = r[k] || [];
                r[k].push(a[i]);
            });
        });
        return r;
    }(info, field);

document.write('<pre>' + JSON.stringify(customer, 0, 4) + '</pre>');

答案 2 :(得分:1)

我想,你几乎就在那里。这样的输出是否符合您的期望?

var field = ["Name", "Age", "Gender"];
var info = [
  ["David", "32", "Male"],
  ["John", "35", "Male"],
  ["Enna", "28", "Female"],
  ["Watson", "22", "Female"]
];

var customers = field.map(function(key, index) {
  var item = {};
  item[key] = info.map(function(dataItem) {
    return dataItem[index];
  });
  return item;
});