简体   繁体   English

如何循环对象并从中删除所有功能

[英]How to loop an object and remove all functions from it

Let's get right the issue, I need to remove all functions from a object to send via socket.io JSON! 让我们解决这个问题,我需要从对象中删除所有函数以通过socket.io JSON发送! Let's say I have an object such as... 假设我有一个对象,例如...

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

and I need to convert it too 我也要转换

let myObject = {
    test1: "abc",
    test3: {
        test4: "another string",
        test6: 123
    }
}

I have tried many cod methods, all of which failed! 我尝试了许多鳕鱼方法,但都失败了! I would post them but that would be wasting your valuable time. 我会发布它们,但这将浪费您的宝贵时间。 I'd love anyone who could fix this problem in a neat function manner. 我很乐意以一种精巧的功能解决此问题的任何人。 Yours Truly, Jacob Morris 真的,雅各布·莫里斯(Jacob Morris)

PS Here is a piece of c**p attempt at doing this 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 } } let i = []; function tsfr(ls) { let i = {}; for (let a in ls) { if (typeof(ls[a]) !== "function") { let d = ls[a]; if (typeof(d) == "object") { d = tsfr(d); } i[a] = d; } } return i; } i = tsfr(myObject); console.log(i) 

You can write your own recursive solution, but I think it is better to use JSON.stringify . 您可以编写自己的递归解决方案,但我认为使用JSON.stringify更好。 By default stringify ignores functions and removes them from the result. 默认情况下,stringify会忽略函数并将其从结果中删除。 In certain cases, it's second param, replacer function, can get handy for more advanced object manipulation. 在某些情况下,第二个参数是替换函数,可以用于更高级的对象操作。

 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)); 

(Or on codepen ) (或在Codepen上

Please note that stringifying uses toString() method, and for some instances of custom classes can lead to a data loss. 请注意,字符串化使用toString()方法,对于某些自定义类实例,可能会导致数据丢失。 To prevent that, you'll need to write your own, recursive solution. 为避免这种情况,您需要编写自己的递归解决方案。 It is probably going to be a lot more complicated. 它可能会变得更加复杂。

Hope this helps, cheers! 希望这会有所帮助,加油!

EDIT: I just saw your attempt. 编辑:我刚刚看到了您的尝试。 It is a step in right direction, but it needs some more love. 这是朝正确方向迈出的一步,但还需要更多的爱。 But I need to advise you against variable names like tsfr or ls . 但是我需要建议您不要使用像tsfrls这样的变量名。 Code is much more readable if you use longer, more descriptive names. 如果使用更长,更具描述性的名称,则代码更具可读性。

EDIT2: As pointed by Andreas in the comments, you don't even need custom replacer as stringify ignores them and removes them by default. EDIT2:正如Andreas在评论中指出的那样,您甚至不需要自定义替换器,因为stringify会忽略它们并默认将其删除。

You can use delete and recursively remove nested object properties it like this: 您可以像这样使用delete和递归地删除嵌套对象属性:

 let myObject = { test1: "abc", test2: function() { console.log("This is a function"); }, test3: { test4: "another string", test5: function() { console.log("another function"); }, test6: 123 } } const deleteFunctions = (obj) => { Object.keys(obj).forEach(k => { if (typeof obj[k] === "function") delete obj[k]; else if (typeof obj[k] === "object") deleteFunctions(obj[k]) }) } deleteFunctions(myObject) console.log(myObject) 

You could filter the key/value pairs by type checking and later map new object by checking the nested objects. 您可以通过类型检查来筛选键/值对,然后通过检查嵌套对象来映射新对象。

 const removeFn = object => Object.assign(...Object .entries(object).filter(([k, v]) => typeof v !== 'function') .map(([k, v]) => ({ [k]: v && typeof v === 'object' ? removeFn(v) : v })) ); var object = { test1: "abc", test2: function() { console.log("This is a function"); }, test3: { test4: "another string", test5: function() { console.log("another function"); }, test6: 123 } }; console.log(removeFn(object)); 

Just for fun, I'd do it this way. 只是为了好玩,我会这样做。 This is a revisitation of Douglas Crockford's DOM algorithms. 这是对Douglas Crockford的DOM算法的重新审视。

First, a recursive function ( visit() ) that visits an arbitrary object and applies an arbitrary function to each member: 首先,一个递归函数( visit() )访问一个任意对象并将一个任意函数应用于每个成员:

function visit(obj, func)
{
  for (k in obj)
  {
    func(obj, k);

    if (typeof obj[k] === "object")
    {
      visit(obj[k], func);
    }
  }
}

This is a working example with a payload function that just outputs found functions to the console: 这是一个带有有效负载功能的工作示例,该功能仅将找到的功能输出到控制台:

 var testdata = { "a": 1, "b": "hello", "c": [ 1, 2, 3 ], "d": (x) => 2 * x, "e": null, "f": { "x": 10, "y": { "z": "$$$", "zz": (x) => 0 } } }; function visit(obj, func) { for (k in obj) { func(obj, k); if (typeof obj[k] === "object") { visit(obj[k], func); } } } visit(testdata, (obj, k) => { if (typeof obj[k] === "function") { console.log(k + " is a function"); } }); 

As the code above shows, the payload function func is able to find all and only functions in the object. 如上面的代码所示,有效载荷函数func能够找到对象中的所有函数。

All we need now is a function that removes the member, but this is very easy now: 现在我们需要的是一个删除成员的函数,但这现在很容易:

(obj, k) => {
  if (typeof obj[k] === "function")
  {
    delete obj[k];
  }
}

By separating the visit from the payload you can reuse this in many ways and manipulate recursively objects for all kinds of necessities... 通过将访问与有效负载分开,您可以以多种方式重用此访问,并为各种必需品递归操作对象...

It will remove all the function from the above object 它将删除上述对象的所有功能

function removeFuncFromObj(obj) {
  Object.keys(obj).map((key) => {
    if (typeof obj[key] === "function") {
        delete obj[key];
    }
    if (typeof obj[key] === typeof {}) {
        removeFuncFromObj(obj[key]);
    }
  });
  return obj;
}
removeFuncFromObj(myObject);

[ https://jsbin.com/favikej/edit?js,console,output][1] [ https://jsbin.com/favikej/edit?js,console,output][1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从对象javascript中删除函数 - How to remove functions from object javascript 如何从对象输出中删除函数? - How do I remove functions from object output? 如何从 Firestore 获取所有文档并进行循环(云功能) - how to get all documents from Firestore and make a loop (Cloud Functions) 如何从所有数组对象中删除对象属性并通过 api 传递 - How to remove and object property from all array object and and pass by api 如何使用for循环调用对象内所有方法内的所有函数? - How do you use a for loop to call all functions inside all methods inside an object? JS如何在forEach循环中从数组中删除对象? - JS How to remove an object from array in a forEach loop? 如何通过使用for循环从javascript中的变量中删除数组对象? - How to remove array object from a variable in javascript by using for loop? 如何从游戏循环内的数组中删除 object (setInterval) - How to remove an object from an array inside a game loop (setInterval) 使用对象和函数从数组中删除对象 - Remove an object from array with objects and functions 如何从javascript对象中删除所有嵌套的数组和对象 - How to remove all nested arrays and objects from javascript object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM