Akshay Thakur
Akshay Thakur

Reputation: 33

How to create new array using element of existing array?

I am having JSON array in that one object contain many keyvaluepair records, but I want only few key records. how to create new array using keys?

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"
 }
]

I want array like this for some operation:

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

Upvotes: 2

Views: 75

Answers (4)

Stano
Stano

Reputation: 86

Single line working solution:

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

Upvotes: 0

Axiome
Axiome

Reputation: 835

Use map operator:

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

Stackblitz

Upvotes: 1

mbojko
mbojko

Reputation: 14679

That's what map does.

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

Upvotes: 0

Adrita Sharma
Adrita Sharma

Reputation: 22213

Try like this:

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

Working Demo

Upvotes: 1

Related Questions