Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Keeping only certain properties in a JavaScript object without wasting too much if your time.
The question is published on by Tutorial Guruji team.
The question is published on by Tutorial Guruji team.
I have an object. I would like to modify the object (not clone it) by removing all properties except for certain specific properties. For instance, if I started with this object:
var myObj={ p1:123, p2:321, p3:{p3_1:1231,p3_2:342}, p4:'23423', //.... p99:{p99_1:'sadf',p99_2:234}, p100:3434 }
and only want properties p1, p2, and p100, how can I obtain this object:
var myObj={ p1:123, p2:321, p100:3434 }
I understand how I could do this with brute force, but would like a more elegant solution.
Answer
Just re-initialise the object:
myObj = { p1: myObj.p1, p2: myObj.p2, p100: myObj.p100 };
Another way is to delete certain properties, which is less effective:
var prop = ['p1', 'p2', 'p100']; for (var k in myObj) { if (prop.indexOf(k) < 0) { delete myObj[k]; } }
We are here to answer your question about Keeping only certain properties in a JavaScript object - If you find the proper solution, please don't forgot to share this with your team members.