![](/img/trans.png)
[英]Make array of flattened out value from nested array object in Javascript
[英]Javascript: get value from nested array of object and make it an object key
我有一個這樣的數組 object
{
"data": [{
"location": {
"type": "Point",
"coordinates": [
77.361916,
28.606075
]
},
}]
}
我想從中獲取緯度和經度並將 object 變為如下所示:
{
"data": [{
"latitude": 28.606075,
"longitude": 77.361916,
}]
}
我怎樣才能做到這一點? 我試着做
response.map((data: any) => {
console.log(data.location);
let latitude = data.location.coordinates[2];
let longitude = data.location.coordinates[1];
delete data.location;
data.latitude = latitude;
data.longitude = longitude;
})
我知道這是錯誤的,但我該如何解決呢?
如果你只有一套
const oldObj = { "data": [{ "location": { "type": "Point", "coordinates": [ 77.361916, 28.606075 ] }, }] } const [longitude, latitude] = [...oldObj.data[0].location.coordinates] const newObj = { data: [{ latitude, longitude }] } console.log(newObj)
更多
const oldArr = [{ "data": [{ "location": { "type": "Point", "coordinates": [ 77.361916, 28.606075 ] }, }] }, { "data": [{ "location": { "type": "Point", "coordinates": [ 77.361916, 28.606075 ] }, }] }, { "data": [{ "location": { "type": "Point", "coordinates": [ 77.361916, 28.606075 ] }, }] } ] const newArr = oldArr.map(item => { const [longitude, latitude] = [...item.data[0].location.coordinates]; return { data: [{ latitude, longitude }] } }) console.log(newArr)
response.map((data: any) => {
let newData = {"data" : []};
let coords = {
'latitude' : data.location.coordinates[2],
'longitude' : data.location.coordinates[1]
}
newData.data.push(coords)
return newData;
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.