gpt4 book ai didi

javascript - 将数组映射到以奇数元素为键、偶数元素为值的对象

转载 作者:行者123 更新时间:2023-11-28 11:29:54 26 4
gpt4 key购买 nike

标题应该是不言自明的。如何转动以下数组:

[
"Bargain",
"deal",
"Consistent",
"Steady; regular",
"Accurately",
"a thing bought or offered for sale much more cheaply than is usual or expected.",
"Charge",
"demand (an amount) as a price for a service rendered or goods supplied."
]

进入下面的数组:

[
{"Bargain": "deal"},
{"Consistent": "Steady; regular"},
{"Accurately": "a thing bought or offered for sale much more cheaply than is usual or expected."},
{"Charge": "demand (an amount) as a price for a service rendered or goods supplied."}
]

解决方案可能很简单,但我无法找到实现它的简单方法。我尝试制作两个单独的数组,并通过取出第一个数组中的奇数值和第二个数组中的偶数值来过滤每个数组的元素,然后再将它们合并,但这似乎有点过分了。

有没有简单的方法可以实现?

(是的,我知道“准确”的定义......很奇怪)

最佳答案

您可以通过简单的 for 循环来做到这一点:

const data = [
"Bargain",
"deal",
"Consistent",
"Steady; regular",
"Accurately",
"a thing bought or offered for sale much more cheaply than is usual or expected.",
"Charge",
"demand (an amount) as a price for a service rendered or goods supplied."
];

let result = [];

for (let i = 0; i < data.length; i += 2) {
result.push({
[data[i]]: data[i + 1]
});
}

console.log(result);

关于javascript - 将数组映射到以奇数元素为键、偶数元素为值的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54632753/

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