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.
it's Order of iteration in loop, In Map it follows the order as it was set while creation whereas in OBJECT does not.
The same way, JavaScript objects can have properties, which define their characteristics.
freeze() The Object. freeze() method freezes an object. Freezing an object prevents extensions and makes existing properties non-writable and non-configurable.
JavaScript objects have two types of properties: data properties and accessor properties.
JavaScript Properties Properties are the values associated with a JavaScript object. A JavaScript object is a collection of unordered properties. Properties can usually be changed, added, and deleted, but some are read only.
Omitting Properties From an Object If we want to omit any number of properties from a JavaScript object, we can implement the following omit function: function omit(obj,...props) { const result = {...obj }; props.forEach(function(prop) { delete result[prop]; }); return result; } Again, let’s use the same person object to see this in action.
Selecting Properties from an Object. If we want to select any number of properties from a JavaScript object, we can implement the following pick function: function pick(obj, ...props) { return props.reduce(function(result, prop) { result[prop] = obj[prop]; return result; }, {}); } Let’s see this in action!
A property explicitly declared in the object literal is own. But a property that object receives from its prototype is inherited. Let's create an object personB and set its prototype to person: personB object has an own property .profession, and inherits .name and .surname properties from its prototype person.
This was the first hit when googling 'js keep only certain keys' so might be worth an update.
The most 'elegant' solution might just be using underscore.js
_.pick(myObj, 'p1', 'p2', 'p100')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With