我有标头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"]
答案 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
的数据
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;
});