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

Truy cập nested object an toàn bằng string key trong JavaScript

Truy cập property lồng sâu (deep nested) dễ gây lỗi Cannot read property of undefined. Nên dùng thư viện tested như **Lodash**.

Lodash _.get()

const _ = require("lodash");
let obj = { a: { b: { foo: "test" }, c: 2 } };

console.log(_.get(obj, "a.b.foo"));   // "test"
console.log(_.get(obj, "a.c"));       // 2
console.log(_.get(obj, "a.test"));    // undefined
console.log(_.get(obj, "a.test.x"));  // undefined (không throw)

Custom getProp (không dependency)

const getProp = (object, path) => {
  if (path.length === 1) return object[path[0]];
  if (path.length === 0) throw new Error("Empty path");
  if (object[path[0]]) return getProp(object[path[0]], path.slice(1));
  return undefined;
};

// Usage
console.log(getProp(obj, ["a", "b"])); // { foo: "test" }

Optional Chaining (ES2020) — Native way

obj?.a?.b?.foo; // "test" hoặc undefined (không throw)

Khuyến nghị: Dùng ?. (optional chaining) cho code modern. Lodash cho legacy support hoặc dynamic path string.