如何将对象转换为数组?

时间:2020-11-11 03:35:14

标签: javascript jquery

Noob,任何人都可以帮助我将我在API调用中接收到的该对象转换为如下所述的数组,而且该对象将是动态的,即记录长度可以更改。预先感谢。

myObject = {
  "records": [{
      "id": "recDBqsW7C3Dk3HMd",
      "fields": {
        "Latitude": "24.898907",
        "Longitude": "67.117303",
        "CustomerName": "Asad"
      },
      "createdTime": "2020-10-07T04:43:31.000Z"
    },
    {
      "id": "recGlfTbUcEvP46Lf",
      "fields": {
        "Latitude": "24.907641",
        "Longitude": "67.1088035",
        "CustomerName": "Umar"
      },
      "createdTime": "2020-10-07T04:44:11.000Z"
    },
    {
      "id": "recfsQsoznDyWPDe8",
      "fields": {
        "Latitude": "24.911112",
        "Longitude": "67.105117",
        "CustomerName": "Ali"
      },
      "createdTime": "2020-10-06T09:11:05.000Z"
    }
  ]
};

类似:

myArray = [{
    "lat": 24.898907,
    "lon": 67.117303,
    "name": "Asad"
  },
  {
    "lat": 24.907641,
    "lon": 67.1088035,
    "name": "Umar"
  },
  {
    "lat": 24.911112,
    "lon": 67.105117,
    "name": "Ali"
  }
]

2 个答案:

答案 0 :(得分:4)

这可以使用Array.prototype.map函数来完成。

const input = {
  "records": [{
      "id": "recDBqsW7C3Dk3HMd",
      "fields": {
        "Latitude": "24.898907",
        "Longitude": "67.117303",
        "CustomerName": "Asad"
      },
      "createdTime": "2020-10-07T04:43:31.000Z"
    },
    {
      "id": "recGlfTbUcEvP46Lf",
      "fields": {
        "Latitude": "24.907641",
        "Longitude": "67.1088035",
        "CustomerName": "Umar"
      },
      "createdTime": "2020-10-07T04:44:11.000Z"
    },
    {
      "id": "recfsQsoznDyWPDe8",
      "fields": {
        "Latitude": "24.911112",
        "Longitude": "67.105117",
        "CustomerName": "Ali"
      },
      "createdTime": "2020-10-06T09:11:05.000Z"
    }
  ]
};

const output = input.records.map(({ fields }) => ({
  lat: fields.Latitude,
  lan: fields.Longitude,
  name: fields.CustomerName
}));
console.log(output);

答案 1 :(得分:0)

如果平台不支持map函数,则可以使用for...of循环。

const input = {
  "records": [{
      "id": "recDBqsW7C3Dk3HMd",
      "fields": {
        "Latitude": "24.898907",
        "Longitude": "67.117303",
        "CustomerName": "Asad"
      },
      "createdTime": "2020-10-07T04:43:31.000Z"
    },
    {
      "id": "recGlfTbUcEvP46Lf",
      "fields": {
        "Latitude": "24.907641",
        "Longitude": "67.1088035",
        "CustomerName": "Umar"
      },
      "createdTime": "2020-10-07T04:44:11.000Z"
    },
    {
      "id": "recfsQsoznDyWPDe8",
      "fields": {
        "Latitude": "24.911112",
        "Longitude": "67.105117",
        "CustomerName": "Ali"
      },
      "createdTime": "2020-10-06T09:11:05.000Z"
    }
  ]
};

const output = [];

for(let record of input.records){
    output.push({
        lat: record.fields.Latitude,
        lan: record.fields.Longitude,
        name: record.fields.CustomerName
    })
}

console.log(output);

相关问题