JavaScript 函数提取对象及其所有子对象内的所有字符串

Ahm*_*sam 1 javascript

我想构建一个可以从对象及其所有子对象获取所有字符串的函数。

儿童人数未知。此外,它可以是对象或数组。甚至是数组对象。

我用递归构建了一个,但最终我只得到了对象或其子对象中的第一个字符串。每当函数找到一个字符串时,它就会停止并且不再调用!

const findErrorString = (error) => {
  switch (errors.constructor) {
    case String:
      return error;
    case Object:
      const childError = Object.keys(errors).map((key) => {
        return error[key];
      });

      return findErrorString(childError);
    case Array:
      const childError = error.map((item) => {
        return item;
      });

      return findErrorString(childError);

    default:
      return "Oh i didn't find any error.";
  }
};
Run Code Online (Sandbox Code Playgroud)

Axn*_*yff 5

类似的东西应该有效:

const getAllStrings = (arg) => {
  if (typeof arg === "string") {
    return [arg];
  }

  // handle wrong types and null
  if (typeof arg !== "object" || !arg) {
    return [];
  }

  return Object.keys(arg).reduce((acc, key) => {
    return [...acc, ...getAllStrings(arg[key])];
  }, []);
};

console.log(getAllStrings({
  foo: ["str", "str2"],
  bar: {
    abc: "str3",
    def: ["str4"],
    ijk: {
      a3: "str5",
    }
  },
})); // ['str, 'str2', 'str3', 'str4', 'str5']
Run Code Online (Sandbox Code Playgroud)