我有一个数组
super = ["Month 1","22 - Feb - 2024","29 - Feb - 2024","7 - Mar - 2024", "Month 2","23 - Mar - 2024","30 - Mar - 2024","6 - Apr - 2024"].
我想将以下键添加到每 4 个元素中:
keys=["tp","early","target","late"]
我的最终数组看起来像
final=[tp:"Month 1",early:"22 - Feb - 2024",target:"29 - Feb - 2024",late:"7 - Mar - 2024", tp:"Month 2",early:"23 - Mar - 2024",target:"30 - Mar - 2024",late:"6 - Apr - 2024"]
.map()
可能是一个选项,但我不确定如何循环每个第四个元素,而且我对此也不太熟悉。我认为类似 for (var i = 0; i < super.length; i += 4) {stuff}
的东西会起作用,但不确定在“东西”部分要做什么。
这将为您提供所需的输出。
super.map((s, i) => ({[keys[i%4]]: d}))
小故障:
super.map((s, i) => {
//we used [remainder operator][1] here.
const correctKey = keys[i % 4];
//this is the syntax used for assigning object key from string value.
return { [correctKey]: s };
});