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

Truy cập nested JSON object trong JavaScript

Nested object: object nằm bên trong object khác. Truy cập qua chuỗi property: obj.level1.level2.level3.

Ví dụ 1: Single nesting

<script>
  const person = {
    name: 'Ram',
    age: 27,
    vehicles: {
      car: 'Limousine',
      bike: 'KTM Duke',
      plane: 'Lufthansa'
    }
  };

  // Dot notation
  document.write('Mr Ram has a car called ' + person.vehicles.car);
  // "Mr Ram has a car called Limousine"
</script>

Ví dụ 2: Double nesting (Nested sâu hơn)

<script>
  const person = {
    name: 'Ram',
    vehicles: {
      car: 'Limousine',
      airlines: {
        lufthansa: 'Air123',
        'British Airways': 'Brt707' // Key có space → phải dùng bracket
      }
    }
  };

  // Dot notation cho key hợp lệ
  document.write('Plane: ' + person.vehicles.airlines.lufthansa); // Air123

  // Bracket notation cho key có space/ky tự đặc biệt
  document.write('Plane: ' + person.vehicles.airlines['British Airways']); // Brt707
</script>

An toàn với Optional Chaining (ES2020)

// Nếu vehicles hoặc airlines có thể undefined
const airlineCode = person?.vehicles?.airlines?.lufthansa; // undefined thay vì throw error
const baCode = person?.vehicles?.airlines?.['British Airways'];

Duyệt nested object

function printNested(obj, prefix = '') {
  for (const [key, value] of Object.entries(obj)) {
    const path = prefix ? `${prefix}.${key}` : key;
    if (value && typeof value === 'object' && !Array.isArray(value)) {
      printNested(value, path);
    } else {
      console.log(`${path} = ${value}`);
    }
  }
}

printNested(person);
// name = Ram
// vehicles.car = Limousine
// vehicles.airlines.lufthansa = Air123
// vehicles.airlines.British Airways = Brt707

JSON vs JavaScript Object

  • JSON: Chuỗi text, format chuẩn dữ liệu — cần JSON.parse() để thành JS object.
  • JS Object: Đã parse, sẵn sàng truy cập property.
const jsonStr = '{"user":{"profile":{"name":"Alice"}}}';
const obj = JSON.parse(jsonStr);
console.log(obj.user.profile.name); // Alice

Lưu ý

    Key có space, ký tự đặc biệt, hoặc bắt đầu bằng số → bắt buộc bracket notation.
  • Optional chaining ?. chỉ dùng để đọc, không dùng để gán.
  • Deep clone nested object: JSON.parse(JSON.stringify(obj)) (mất function, Date, RegExp) hoặc structuredClone(obj) (modern, hỗ trợ circular).