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"
 }
]
Aravind
  • 40,391
  • 16
  • 91
  • 110
  • You could use [`Array.Map`](https://www.w3schools.com/jsref/jsref_map.asp) – Igor Sep 27 '19 at 15:09
  • destructuring https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment – Shilly Sep 27 '19 at 15:11
  • Possible duplicate of [From an array of objects, extract value of a property as array](https://stackoverflow.com/questions/19590865/from-an-array-of-objects-extract-value-of-a-property-as-array) – Igor Sep 27 '19 at 15:13

4 Answers4

1

Try like this:

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

Working Demo

Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79
1

Use map operator:

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

Stackblitz

Axiome
  • 695
  • 5
  • 18
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));
mbojko
  • 13,503
  • 1
  • 16
  • 26
0

Single line working solution:

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