Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

กรองคอลเลกชันซ้อนด้วย JavaScript

สมมติว่าเรามีอาร์เรย์ของอ็อบเจ็กต์ซ้อนแบบนี้:

const arr = [{
  id: 1,
  legs:[{
    carrierName:'Pegasus'
  }]
}, {
  id: 2,
  legs:[{
    carrierName: 'SunExpress'
  },
  {
    carrierName: 'SunExpress'
  }]
}, {
  id: 3,
  legs:[{
    carrierName: 'Pegasus'
  },
  {
    carrierName: 'SunExpress'
  }]
}];

เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ดังกล่าวเป็นอาร์กิวเมนต์แรก และสตริงค้นหาเป็นอาร์กิวเมนต์ที่สอง ฟังก์ชันควรกรองอาร์เรย์ให้เหลือเฉพาะอ็อบเจ็กต์ที่คุณสมบัติ "carrier name" มีค่าเท่ากับค่าที่ระบุโดยอาร์กิวเมนต์ที่สอง

ถ้าสำหรับอาร์เรย์ข้างต้น อาร์กิวเมนต์ที่สองคือ "Pegasus" ผลลัพธ์ควรเป็นดังนี้:

const output = [{
  id: 1,
  legs:[{
    carrierName:'Pegasus'
  }]
}, {
  id: 3,
  legs:[{
    carrierName: 'Pegasus'
  },
  {
    carrierName: 'SunExpress'
  }]
}];

ตัวอย่างโค้ด

โค้ดสำหรับทำสิ่งนี้คือ:

const arr = [{
  id: 1,
  legs:[{
    carrierName:'Pegasus'
  }]
}, {
  id: 2,
  legs:[{
    carrierName: 'SunExpress'
  },
  {
    carrierName: 'SunExpress'
  }]
}, {
  id: 3,
  legs:[{
    carrierName: 'Pegasus'
  },
  {
    carrierName: 'SunExpress'
  }]
}];
const keys = ['Pegasus'];
const filterByKeys = (arr = [], keys = []) => {
  const res = arr.filter(function(item) {
    const thisObj = this;
    return item.legs.some(leg => {
      return thisObj[leg.carrierName];
    });
  }, keys.reduce((acc, val) => {
    acc[val] = true;
    return acc;
  }, Object.create(null)));
  return res;
}
console.log(JSON.stringify(filterByKeys(arr, keys), undefined, 4));

ผลลัพธ์

ผลลัพธ์ในคอนโซลจะเป็นดังนี้:

[
  {
    "id": 1,
    "legs": [
      {
        "carrierName": "Pegasus"
      }
    ]
  },
  {
    "id": 3,
    "legs": [
      {
        "carrierName": "Pegasus"
      },
      {
        "carrierName": "SunExpress"
      }
    ]
  }
]