-2

请帮助我知道如何在下面的示例中提取以逗号分隔的每个数组元素:

 array = [37.421998333333335: -122.08400000000002, 35.71529801212532: 51.39060813566725]

我试过 slice ,它不适用于上述情况。请帮助我知道解决方案是什么。最后,我想将每个元素提取为如下对象:

  {'37.421998333333335': -122.08400000000002}
   
4

1 回答 1

0

您的 JavaScript 无效。它需要是一个对象或一个数组,而不是两者的组合。

如果你有一个对象

const
  coords = { 37.421998333333335: -122.08400000000002, 35.71529801212532: 51.39060813566725 },
  pairs = Object.entries(coords).map(entry => Object.fromEntries([entry]));

console.log(pairs);
.as-console-wrapper { top: 0; max-height: 100% !important; }

如果你有一个数组

const
  coords = [ 37.421998333333335, -122.08400000000002, 35.71529801212532, 51.39060813566725 ],
  pairs = new Array(coords.length / 2).fill(0)
    .reduce((r, e, i, a) => [...r, [ coords[i * 2], coords[i * 2 + 1] ]], [])
    .map(entry => Object.fromEntries([entry]));

console.log(pairs);
.as-console-wrapper { top: 0; max-height: 100% !important; }

于 2021-03-02T13:13:54.617 回答