提问者:小点点

JavaScript:从对象的嵌套数组中获取值并使其成为对象键


我有一个像这样对象数组

{
  "data": [{
    "location": {
      "type": "Point",
      "coordinates": [
        77.361916,
        28.606075
      ]
    },
  }]
}

我想从中得到纬度和经度,并将对象变异为如下所示:

{
  "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;
})

我知道这是不对的,但我该怎么解决呢?


共2个答案

匿名用户

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;
})

匿名用户

如果只有一套,分两步

null

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)