从对象数组构造新的对象数组

时间:2018-04-04 20:05:10

标签: javascript arrays object

我有一个来自api的对象数组,包含我需要存储到另一个对象数组的纬度和经度。

response: [
  {
    title: "Map marker 1",
    lat: 10.0,
    lng: 10.0
  },
  {
    title: "Map marker 2",
    lat: 11.0,
    lng: 11.0
  }
]

获取latlng值并将它们存储到具有以下结构的新对象数组的首选方法是什么?

markers: [
   {
     position: {lat: 10.0, lng: 10.0}
   }, 
   {
     position: {lat: 11.0, lng: 11.0}
   }
]

4 个答案:

答案 0 :(得分:1)

使用Array.prototype.map可能是最明显的方法。它允许您将每个数组元素转换为您想要的形状。



let response = [
  {
    title: "Map marker 1",
    lat: 10.0,
    lng: 10.0
  },
  {
    title: "Map marker 2",
    lat: 11.0,
    lng: 11.0
  }
];

let markers = response.map(r => {
  return {
     position: {lat: r.lat, lng: r.lng}
   }
});

console.log(markers);




答案 1 :(得分:1)

使用Array.from

的替代方案



var response = [  {    title: "Map marker 1",    lat: 10.0,    lng: 10.0  },  {    title: "Map marker 2",    lat: 11.0,    lng: 11.0  }],
    markers = Array.from(response, ({lat, lng}) => ({position: {lat, lng}}));

console.log(markers);

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




最快(性能)方法是使用for-loop



var response = [  {    title: "Map marker 1",    lat: 10.0,    lng: 10.0  },  {    title: "Map marker 2",    lat: 11.0,    lng: 11.0  }],
    markers = [];

for (var i = 0; i < response.length; i++) {
  markers[i]   = {position: { lat: response[i].lat, lng: response[i].lng }};
}

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

答案 2 :(得分:0)

您可以使用所需属性的Array#mapdestructuring assignment与值一起使用,然后将short hand properties用于新对象。

&#13;
&#13;
var response = [{ title: "Map marker 1", lat: 10.0, lng: 10.0 }, { title: "Map marker 2", lat: 11.0, lng: 11.0 }],
    array = response.map(({ lat, lng }) => ({ position: { lat, lng } }));

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

答案 3 :(得分:0)

response = [
  {
    title: "Map marker 1",
    lat: 10.0,
    lng: 10.0
  },
  {
    title: "Map marker 2",
    lat: 11.0,
    lng: 11.0
  }
];

markers = [];

for (var i in response) {
  markers.push({position: {lat: response[i].lat, lng: response[i].lng}});
}

// Some programmers hate the loop upstairs, so you can do like this and have exactly the same result:
for (var i = 0; i < response.length; i++) {
  markers.push({position: {lat: response[i].lat, lng: response[i].lng}});
}

// Other programmers believe and I don't know why that map is better, so:
markers = response.map(function (item) {
  return {position: {lat: item.lat, lng: item.lng}};
});

// The world is full of boring people, so we have programmers that think that only ECMA6 works, so:
markers = response.map(item => {position: {lat: item.lat, lng: item.lng});

// With any of those codes you will have this:
markers = [
  {
    position: {lat: 10.0, lng: 10.0}
  }, 
  {
    position: {lat: 11.0, lng: 11.0}
  }
]