gpt4 book ai didi

javascript - 将键添加到数组然后组合(有更好的方法吗?)

转载 作者:行者123 更新时间:2023-11-28 12:55:24 25 4
gpt4 key购买 nike

我目前有两个从 API 收到的数组,如下所示:

["Array1", "Array1", "Array1"]
["Array2", "Array2", "Array2"]

我想向它们添加键,所以它们看起来像这样:

[{date: "Array1"}, {date: "Array1"}, {date: "Array1"}]
[{data: "Array2"}, {data: "Array2"}, {data: "Array2"}]

然后将它们组合起来是这样的:

[
{date: "Array1", data: "Array2"},
{date: "Array1", data: "Array2"},
{date: "Array1", data: "Array2"},
]

我想我已经通过这段代码得到了我想要的东西:

var Array1 = ["Array1", "Array1", "Array1"];
var Array2 = ["Array2", "Array2", "Array2"];
var newArray1 = Array1.map((i) => ({
date: i
}))
var newArray2 = Array2.map((i) => ({
data: i
}))

var combined = [];
for (var i = 0; i < newArray1.length; i++) {
combined.push({
...newArray1[i],
...newArray2[i]
});
}

console.log(combined);

有更好的方法吗?

最佳答案

您可以映射Array1来获取日期,并通过索引从Array2获取数据:

var Array1 = ["Array1", "Array1", "Array1"];
var Array2 = ["Array2", "Array2", "Array2"];

var combined = Array1.map((date, i) => ({
date,
data: Array2[i]
}))

console.log(combined)

关于javascript - 将键添加到数组然后组合(有更好的方法吗?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56066342/

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