Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Sửa property của nested object trong JavaScript

Truy cập property lồng nhau bằng dot notation (obj.a.b) hoặc bracket notation (obj['a']['b']). Cả hai tương đương về chức năng.

Dot Notation

<script>
  const person = {
    name: 'Ram',
    age: 27,
    address: { houseNo: 123, street: 'Baker Street', country: 'England' }
  };

  document.write('Trước: ' + person.address.country + '<br>'); // England
  person.address.country = 'India'; // Sửa trực tiếp
  document.write('Sau: ' + person.address.country); // India
</script>

Bracket Notation

<script>
  const person = {
    name: 'Ram',
    address: { country: 'England' }
  };

  document.write('Trước: ' + person.address['country'] + '<br>'); // England
  person.address['country'] = 'India'; // Key trong ngoặc vuông
  document.write('Sau: ' + person.address['country']); // India
</script>

Khi nào dùng bracket notation?

  • Key có ký tự đặc biệt: obj['first-name'], obj['123'].
  • Key lưu trong biến: const key = 'country'; obj.address[key] = 'India';.
  • Key là số (array index): arr[0].

An toàn: Optional Chaining (ES2020)

Tránh lỗi Cannot read property of undefined khi path trung gian null/undefined.

// Cũ: phải check từng level
if (person && person.address && person.address.country) { ... }

// Mới: optional chaining ?.
person?.address?.country = 'India'; // Gán an toàn (chỉ đọc, không gán được qua ?.)
// Lưu ý: ?. không dùng được ở vế trái gán. Cần:
if (person?.address) person.address.country = 'India';

Immutable Update (Không mutate gốc) — Pattern phổ biến React/Redux

// Spread operator (shallow)
const updated = {
  ...person,
  address: {
    ...person.address,
    country: 'India'
  }
};

// Hoặc dùng Immer (thư viện) cho deep update dễ dàng
import { produce } from 'immer';
const updated = produce(person, draft => {
  draft.address.country = 'India';
});

Tóm tắt

CáchCú phápDùng khi
Dotobj.a.b = valKey hợp lệ identifier, tĩnh
Bracketobj['a']['b'] = valKey động, có ký tự đặc biệt, số
Optional chaining (đọc)obj?.a?.bPath có thể null/undefined
Immutable update{...obj, a: {...obj.a, b: val}}State management (React, Redux)