将数组映射到对象,其中奇数元素作为键,偶数元素作为值

时间:2019-02-11 14:29:01

标签: javascript arrays

标题应该很容易解释。我如何打开以下数组:

[
  "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."}
]

解决方案可能很简单,但我想不出一种简单的方法来实现。我尝试制作2个单独的数组,并通过在第一个数组中取出奇数值并在第二个数组中取出偶数值(然后将它们合并之后)将它们过滤掉之后,对每个数组的元素进行过滤,但这似乎有些过分。

有没有简单的方法来实现它?

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

2 个答案:

答案 0 :(得分:6)

您可以通过简单的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);

答案 1 :(得分:2)

您可以像这样使用Array.from

int f = (int)difftime( time(NULL), start ) ;
int min = f / 60 ;
int sec = f % 60 ;