gpt4 book ai didi

javascript - 将 Javascript 响应转换为 Array/Map

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

我有来自 Javascript ElasticSearch 查询的以下响应,我需要将其映射到以下结构。有没有比我目前正在做的更有效的方法来做到这一点?

谢谢

我需要映射到的结构:(其中大约 700 个)

[{
"coordinates": ["48", "37"],
"name": "something",
"population": "501"
},

我返回的数据的当前结构:

[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]

0: Object

_id: "4"
_index: "locationIndex"
_score: 1
_source: Object
coordinates: Array[2]
0: -77.080597
1: 38.892899
length: 2
__proto__: Array[0]
name: "someName"
population: 57205
1: Object
...

我正在尝试但失败了:

 var results= [{
"key": 'coordinates',
resp.coordiantes[0],
resp.coordinates[1],
"key": 'name',
resp.name
})
}];

最佳答案

假设您的数据存储在 myData 变量中,您可以使用 Array.prototype.map 方法来操作它并实现您想要的。这是一个解决方案:

result = myData.map(function(obj) {
return {
coordinates: obj._source.coordinates,
name: obj.name,
population: obj.population
}
});

就这么简单!结果将是这样的:

[
{
"coordinates": [-77.080597, 38.892899],
"name": "some name",
"population": 52701
},
{
"coordinates": [-54.930299, 30.992833],
"name": "some name 2",
"population": 84229
},
{
"coordinates": [-82.001438, -5.38131],
"name": "some name 3",
"population": 5991
} //, ...
]

关于javascript - 将 Javascript 响应转换为 Array/Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29351559/

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