如何映射数组并保留对象的某些属性?

时间:2019-11-21 03:36:54

标签: javascript arrays object

我正在寻找映射和数组并返回仅具有原始对象某些属性的数组。例如从这里:

[
   {
    lat: 40.621996,
    lon: -74.028679,
    places: 1,
    time: "2019/11/20 22:26:00"
   },
   {
    lat: 40.621996,
    lon: -74.028679,
    places: 1,
    time: "2019/11/20 22:26:00"},
   {
    lat: 40.621996,
    lon: -74.028679,
    places: 1,
    time: "2019/11/20 22:26:00"}
   ]

产生这个:

[
   {
    lat: 40.621996,
    lon: -74.028679
   },
   {
    lat: 40.621996,
    lon: -74.028679
    },
   {
    lat: 40.621996,
    lon: -74.028679
   }
   ]

不确定映射是否是思考此问题的正确方法?

5 个答案:

答案 0 :(得分:1)

const list = [
   {
    lat: 40.621996,
    lon: -74.028679,
    places: 1,
    time: "2019/11/20 22:26:00"
   },
   {
    lat: 40.621996,
    lon: -74.028679,
    places: 1,
    time: "2019/11/20 22:26:00"},
   {
    lat: 40.621996,
    lon: -74.028679,
    places: 1,
    time: "2019/11/20 22:26:00"}
   ];
   
const result = list.map( o => { return { lat: o.lat, lon: o.lon} });
// or
const result1 = list.map(({lat, lon}) => ({lat, lon}));

console.log(result);
console.log(result1);

您可以使用map方法

答案 1 :(得分:0)

映射将起作用。

const array = [{
    lat: 40.621996,
    lon: -74.028679,
    places: 1,
    time: "2019/11/20 22:26:00"
  },
  {
    lat: 40.621996,
    lon: -74.028679,
    places: 1,
    time: "2019/11/20 22:26:00"
  },
  {
    lat: 40.621996,
    lon: -74.028679,
    places: 1,
    time: "2019/11/20 22:26:00"
  }
]

const mappedArray = array.map(item => ({
  lat: item.lat,
  lon: item.lon
}));

答案 2 :(得分:0)

let arr=[
   {
    lat: 40.621996,
    lon: -74.028679,
    places: 1,
    time: "2019/11/20 22:26:00"
   },
   {
    lat: 40.621996,
    lon: -74.028679,
    places: 1,
    time: "2019/11/20 22:26:00"},
   {
    lat: 40.621996,
    lon: -74.028679,
    places: 1,
    time: "2019/11/20 22:26:00"}
   ];
   
   console.log(arr.map(({ lat, lon }) => ({lat, lon})));

答案 3 :(得分:0)

const data = [{
    lat: 40.621996,
    lon: -74.028679,
    places: 1,
    time: "2019/11/20 22:26:00"
  },
  {
    lat: 40.621996,
    lon: -74.028679,
    places: 1,
    time: "2019/11/20 22:26:00"
  },
  {
    lat: 40.621996,
    lon: -74.028679,
    places: 1,
    time: "2019/11/20 22:26:00"
  }
];

const res = data.map(({lat, lon}) => ({lat, lon}));

console.log(res);

答案 4 :(得分:0)

您可以使用地图

var data = [
            {
              lat: 40.621996,
              lon: -74.028679,
              places: 1,
              time: "2019/11/20 22:26:00"
            },
            {
             lat: 40.621996,
             lon: -74.028679,
             places: 1,
             time: "2019/11/20 22:26:00"},
            {
             lat: 40.621996,
             lon: -74.028679,
             places: 1,
             time: "2019/11/20 22:26:00"}
             ];

var newData = data.map((d)=>{
 ['places', 'time'].forEach(e => delete d[e]);
 return d;
});