gpt4 book ai didi

javascript : Merge 2 arrays with property and index

转载 作者:行者123 更新时间:2023-11-30 12:03:08 26 4
gpt4 key购买 nike

我有 2 个数组,例如:

a1 = ["k1","k2","k3"];
a2 = ["v1","v2","v3"];

我想要那个:

a3 = ["k1": { myv: "v1" }, "k2": { myv: "v2" }, "k3": { myv: "v3" }];

我使用了一个 forEach,例如:

a1.forEach(function(elem, i) {
a3.push(elem);
a3[i].name = a2[i];
});

但它不起作用,它给了我:

a3 = ["k1","k2","k3"];

那么我该怎么做呢?

请帮帮我。

最佳答案

有了适当的数据结构和单个循环,您可能需要:

var a1 = ["k1", "k2", "k3"],
a2 = ["v1", "v2", "v3"],
result = {};

a1.forEach(function (a, i) {
result[a] = { myv: a2[i] };
});
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

关于javascript : Merge 2 arrays with property and index,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36112312/

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