admin管理员组文章数量:1352314
Let's get right the issue, I need to remove all functions from a object to send via 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
P.S. Here is a piece of c**p attempt at doing this
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)
Let's get right the issue, I need to remove all functions from a object to send via 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
P.S. Here is a piece of c**p attempt at doing this
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)
Share
Improve this question
edited Feb 19, 2019 at 22:20
Jacob Morris
asked Jan 5, 2019 at 9:51
Jacob MorrisJacob Morris
5546 silver badges18 bronze badges
6
- Please show at least one of your attempts. – BenM Commented Jan 5, 2019 at 9:54
- You can do it with the defineProperty method developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – Anoop Mc Commented Jan 5, 2019 at 9:56
- @AnoopMc I looked at that earlier and didn't see anything that would remove all functions of an object – Jacob Morris Commented Jan 5, 2019 at 9:58
-
1
myObject = JSON.parse(JSON.stringify(myObject))
– Andreas Commented Jan 5, 2019 at 9:59 - remove means delete or getting a new object without function? – Nina Scholz Commented Jan 5, 2019 at 10:01
5 Answers
Reset to default 7You can write your own recursive solution, but I think it is better to use JSON.stringify. By default stringify ignores functions and removes them from the result. 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)
Please note that stringifying uses toString()
method, and for some instances of custom classes can lead to a data loss. To prevent that, you'll need to write your own, recursive solution. It is probably going to be a lot more plicated.
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
. Code is much more readable if you use longer, more descriptive names.
EDIT2: As pointed by Andreas in the ments, you don't even need custom replacer as stringify ignores them and removes them by default.
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));
You can use delete
and recursively remove nested object properties it like this:
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)
Just for fun, I'd do it this way. This is a revisitation of Douglas Crockford's DOM algorithms.
First, a recursive function (visit()
) that visits an arbitrary object and applies an arbitrary function to each member:
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.
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./favikej/edit?js,console,output][1]
本文标签: javascriptHow to loop an object and remove all functions from itStack Overflow
版权声明:本文标题:javascript - How to loop an object and remove all functions from it - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743911929a2560557.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论