Skip to content

实现lodash的set和get方法

Posted on:2023年10月30日 at 10:38

下面是提供的参考:

function set(object, path, value) {
  const keys = path.split(".");
  let current = object;

  for (let i = 0; i < keys.length - 1; i++) {
    const key = keys[i];
    if (!(key in current)) {
      // Create nested objects if the key doesn't exist
      current[key] = {};
    }
    current = current[key];
  }

  current[keys[keys.length - 1]] = value;
}

function get(object, path) {
  const keys = path.split(".");
  let current = object;

  for (const key of keys) {
    if (typeof current !== "object" || !(key in current)) {
      return undefined;
    }
    current = current[key];
  }

  return current;
}

下面是使用的示例:

const obj = {
  foo: {
    bar: {
      baz: "Hello, World!",
    },
  },
};

set(obj, "foo.bar.baz", "New Value");
console.log(get(obj, "foo.bar.baz")); // Output: New Value

console.log(get(obj, "foo.bar.qux")); // Output: undefined
原文转自:https://fe.ecool.fun/topic/49ec948f-9b64-4d28-b97f-3796518a6c16