如何使用现有数组的元素创建新数组?

时间:2019-09-27 15:08:39

标签: javascript

我有一个对象包含许多键值对记录的JSON数组,但是我只需要几个键记录。如何使用键创建新数组?

array = [
{
 airlineName: "Airline 1",
 hotelName: "Hotel 1 ", 
 airportId: "456",
 checkInDate: "17 SEP 1998",
 bookingStatus: "B"
},
{
airlineName: "Airline 2",
 hotelName: "Hotel 1", 
 airportId: "123",
 checkInDate: "7 AUG 1998",
 bookingStatus: "P"
 }
]

我想要这样的数组进行某些操作:

array = [
{
 airlineName: "Airline 1",
 hotelName: "Hotel 1 ", 
 bookingStatus: "B"
},
{
airlineName: "Airline 2",
 hotelName: "Hotel 1", 
 bookingStatus: "P"
 }
]

4 个答案:

答案 0 :(得分:1)

尝试这样:

var result = [];
this.array.forEach(item => {
  result.push({
    airlineName: item.airlineName,
    hotelName: item.hotelName,
    bookingStatus: item.bookingStatus
  });
});

Working Demo

答案 1 :(得分:1)

使用地图运算符:

const newArray = this.array.map(element => {
    return {
      airlineName: element.airlineName,
      hotelName: element.hotelName,
      bookingStatus: element.bookingStatus
    };
  });

Stackblitz

答案 2 :(得分:0)

map就是这样。

const array = [{
    airlineName: "Airline 1",
    hotelName: "Hotel 1 ",
    airportId: "456",
    checkInDate: "17 SEP 1998",
    bookingStatus: "B"
  },
  {
    airlineName: "Airline 2",
    hotelName: "Hotel 1",
    airportId: "123",
    checkInDate: "7 AUG 1998",
    bookingStatus: "P"
  }
]


const pickValues = ({
  airlineName,
  hotelName,
  bookingStatus
}) => ({
  airlineName,
  hotelName,
  bookingStatus
});

console.log(array.map(pickValues));

答案 3 :(得分:0)

单行工作解决方案:

this.array.map(x => ({airlineName: x.airlineName, hotelName: x.hotelName, bookingStatus: x.bookingStatus}))