2

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

4 Answers 4

1

Try like this:

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

Working Demo

Sign up to request clarification or add additional context in comments.

3 Comments

Isn't that just a truthy expression resulting in an array of booleans?
Not the most elegant way of doing it but it is working
@Exomus I agree :)
1

Use map operator:

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

Stackblitz

Comments

0

Single line working solution:

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.