循环数组以将键添加到每个第 n 个元素

问题描述 投票:0回答:1

我有一个数组

    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}
的东西会起作用,但不确定在“东西”部分要做什么。

javascript arrays loops key
1个回答
0
投票

这将为您提供所需的输出。

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 };
});
© www.soinside.com 2019 - 2024. All rights reserved.