gpt4 book ai didi

javascript - 组合两个数组以形成 JavaScript 对象

转载 作者:行者123 更新时间:2023-12-03 02:41:21 25 4
gpt4 key购买 nike

我有两个数组:

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 对象,用于行数组中的每个项目。之后,我想将每个对象推送到一个新数组中。

喜欢:

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);

当我知道列名时,我可以这样做,但是当列名未知时,我需要能够以这种方式存储数据 - 即基于列数组的索引。

我之前尝试过这样的:

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)
}

上面的代码仅一次又一次地存储第一项(根据 rows.length)。

我不明白如何将列名与行组合起来创建对象数组。 “行”包含数组这一事实尤其令人困惑。

最佳答案

您也可以以更加以数据为中心的方式执行此操作:

const columns = ["Date", "Number", "Size", "Location", "Age"]

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

const result = rows.map(row =>
row.reduce(
(result, field, index) => ({ ...result, [columns[index]]: field }),
{}
)
)

console.log(result)

2022 年更新:使用现在更常见的语法(短函数)

这是原始片段:

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

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

var result = rows.map(function(row) {
return row.reduce(function(result, field, index) {
result[columns[index]] = field;
return result;
}, {});
});

console.log(result)

这样您就不必处理临时数组。

如果您的代码也可以在古代浏览器上运行,我建议您查看lodash用于使用map + reduce

关于javascript - 组合两个数组以形成 JavaScript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9256257/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com