如何循环一个对象并从中删除所有函数

Jac*_*ris 2 javascript function

让我们解决这个问题,我需要从对象中删除所有函数以通过 socket.io JSON 发送!假设我有一个对象,例如...

let myObject = {
    test1: "abc",
    test2: function() {
        console.log("This is a function");
    },
    test3: {
        test4: "another string",
        test5: function() {
            console.log("another function");
        },
        test6: 123
    }
}
Run Code Online (Sandbox Code Playgroud)

我也需要转换它

let myObject = {
    test1: "abc",
    test3: {
        test4: "another string",
        test6: 123
    }
}
Run Code Online (Sandbox Code Playgroud)

我试过很多鳕鱼的方法,都失败了!我会发布它们,但这会浪费您的宝贵时间。我喜欢任何可以以简洁的功能方式解决此问题的人。您诚挚的,雅各布·莫里斯

PS 这是一个 c**p 尝试这样做

let myObject = {
    test1: "abc",
    test2: function() {
        console.log("This is a function");
    },
    test3: {
        test4: "another string",
        test5: function() {
            console.log("another function");
        },
        test6: 123
    }
}
Run Code Online (Sandbox Code Playgroud)

Sta*_*nko 5

您可以编写自己的递归解决方案,但我认为最好使用JSON.stringify。默认情况下,stringify 会忽略函数并将它们从结果中删除。在某些情况下,它是第二个参数,替换函数,可以方便地进行更高级的对象操作。

const removeFunctions = (obj) => {
  const stringified = JSON.stringify(obj);

  // We need to parse string back to object and return it
  const parsed = JSON.parse(stringified);

  return parsed;
}

const myObject = {
    test1: "abc",
    test2: function() {
        console.log("This is a function");
    },
    test3: {
        test4: "another string",
        test5: function() {
            console.log("another function");
        },
        test6: 123
    }
}

console.log(removeFunctions(myObject));
Run Code Online (Sandbox Code Playgroud)

(或在codepen 上

请注意,字符串化使用toString()方法,并且对于自定义类的某些实例可能会导致数据丢失。为了防止这种情况,您需要编写自己的递归解决方案。它可能会复杂得多。

希望这有帮助,干杯!

编辑:我刚刚看到你的尝试。这是朝着正确方向迈出的一步,但它需要更多的爱。但是我需要建议您不要使用像tsfror 之类的变量名ls。如果您使用更长、更具描述性的名称,代码的可读性会更高。

EDIT2:正如 Andreas 在评论中指出的那样,您甚至不需要自定义替换器,因为 stringify 会忽略它们并默认删除它们。