jsrosetta

Hàm

Destructuring

Destructuring object trong Node.js so với pattern destructuring struct trong Rust, tuple trong Swift, record pattern trong Java và gán nhiều biến trong Go.

Phiên bản tối thiểu
Node.js ≥ 12.20Go ≥ 1.0Rust ≥ 1.58Swift ≥ 2.0Java ≥ 25
Đã chạy thử trên
Node.js 24.12.0Go 1.27.1Rust 1.98.1Swift 6.2.4Java 25.0.4.1

Code Node.js là ES module: lưu file .mjs hoặc đặt "type": "module" trong package.json.

Node.js destructure trực tiếp một object thành nhiều biến bằng cú pháp { key, value } = obj. Rust có cú pháp destructuring struct thật sự qua pattern matching (let Obj { key, value } = obj) — gần với JS nhất. Swift không destructure struct trực tiếp theo tên trường, nhưng destructure tuple thì có (let (key, value) = (...)). Java từ bản 21 có record pattern, destructure được record ngay trong instanceof. Go không có cú pháp destructuring cho struct, nhưng đạt cùng hiệu quả bằng gán nhiều biến cùng lúc hoặc bằng hàm trả về nhiều giá trị.

Lấy nhiều giá trị từ một object

const obj = { key: 'foo', value: 'bar' };
 
const { key, value } = obj;
console.log(key, value); // foo bar

Tham khảo: github.com/miguelmota/golang-for-nodejs-developers#destructuring