ฟังก์ชันสำหรับดึงรายชื่อ Field ทั้งหมดจาก Record และคืนค่าเป็น List ของ Text
= Record.FieldNames(record as record) as list
= Record.FieldNames(record as record) as list
| Argument | Type | Required | Default | Description |
|---|---|---|---|---|
| record | record | Yes | Record ที่ต้องการดึงชื่อ Field ทั้งหมด |
ใช้ดูว่าใน Record มี Field อะไรบ้าง เพื่อนำไปตรวจสอบหรือเปรียบเทียบ
เช่น ใช้ร่วมกับ List.Count เพื่อนับจำนวน Field หรือใช้ในการ Reorder Field
let Source = Record.FieldNames([CustomerID = 1, Name = "Bob", Phone = "123-4567"]) in Sourcelet
Source = Record.FieldNames([CustomerID = 1, Name = "Bob", Phone = "123-4567"])
in
Source
{"CustomerID", "Name", "Phone"}
let Customer = [ID = 1, Name = "Alice", Email = "alice@example.com"], Fields = Record.FieldNames(Customer), HasEmail = List.Contains(Fields, "Email") in HasEmai…let
Customer = [ID = 1, Name = "Alice", Email = "alice@example.com"],
Fields = Record.FieldNames(Customer),
HasEmail = List.Contains(Fields, "Email")
in
HasEmail
true
let Customer = [ID = 100, Name = "John", Amount = 5000], Fields = Record.FieldNames(Customer), Values = List.Transform(Fields, each Record.Field(Customer, _)) i…let
Customer = [ID = 100, Name = "John", Amount = 5000],
Fields = Record.FieldNames(Customer),
Values = List.Transform(Fields, each Record.Field(Customer, _))
in
Values
{100, "John", 5000}
let Product = [SKU = "P123", Name = "Laptop", Price = 29999, Stock = 50], FieldCount = List.Count(Record.FieldNames(Product)) in FieldCountlet
Product = [SKU = "P123", Name = "Laptop", Price = 29999, Stock = 50],
FieldCount = List.Count(Record.FieldNames(Product))
in
FieldCount
4
let EmptyRecord = [], Fields = Record.FieldNames(EmptyRecord) in Fieldslet
EmptyRecord = [],
Fields = Record.FieldNames(EmptyRecord)
in
Fields
{}
ลำดับจะตามที่ปรากฏใน Record ซึ่ง Record ใน Power Query M เป็น Ordered Collection หมายความว่าลำดับ Field มีความสำคัญ ผมทดสอบแล้วลำดับจะไม่เปลี่ยนแปลง แม้ว่าจะสร้าง Record ด้วยวิธีต่างกัน
Record.FieldNames คืนค่าแค่ชื่อ Field เป็น List ของ Text ส่วน Record.FieldValues คืนค่าข้อมูล (Value) ของแต่ละ Field ออกมา ถ้าต้องชื่อให้ใช้ FieldNames ถ้าต้องค่าให้ใช้ FieldValues
ผมทดสอบแล้ว Record ว่าง (Empty Record) จะคืนค่าเป็น List ว่าง {} ไม่มีข้อผิดพลาด ปลอดภัยใช้ได้
ไม่ได้ Record.FieldNames ทำงานกับ Record เท่านั้น ถ้าต้องดึงชื่อ Column จาก Table ให้ใช้ Table.ColumnNames แทน ผมเคยลืมเรื่องนี้เองจึงเตือน
Record.FieldNames คืนค่ารายชื่อ Field ทั้งหมดจาก Record ที่กำหนด โดยเรียงลำดับตามที่ปรากฏใน Record ต่างจาก Record.FieldValues ที่คืนค่าข้อมูล Record.FieldNames ให้เฉพาะชื่อของ Field เท่านั้น
ที่เจ๋งคือสามารถใช้ฟังก์ชันนี้เพื่อตรวจสอบโครงสร้างของ Record แบบ Dynamic ก่อนเข้าถึงข้อมูล เหมาะสำหรับการ Loop ผ่าน Field ทั้งหมด หรือสร้าง Custom Function ที่รองรับ Record ที่มีโครงสร้างไม่แน่นอน
ส่วนตัวผมใช้ Record.FieldNames บ่อยมากเวลาต้องดึงข้อมูลจาก API ที่ Return Structure ไม่แน่นอน หรือต้องเปรียบเทียบว่า Record ขาดฟิลด์อะไรไป