I know that objects can be copied to Javascript
, for example, usingObject.assign()
const target = {};
const source = {a: 1, b: 2, c: 3};
Object.assign(target, source);
console.log(target);
How could I do if I wanted to copy into the variable target
all the properties of the variable source
except, say, b: 2
?
That is, the expected result would be{"a": 1, "c": 3}
A fairly short way for a single level is using destructuring :
In addition
Object.keys
to proposing the-breaker, which is quite useful for giving us the possibility of using array functions (such as.filter()
), there are other forms that can be essential in other scenarios, for example if we have several levels and we do not know the structure of the array. object, using the callbackJSON.parse
saves us some headaches:Another way can be iterating with
for..in
(a single level):In all cases, it can change a lot if what we have is what we want to eliminate or what we want to leave. In these examples I assume we don't want "b", and the others don't matter.
Another way, quite unreadable, is combining
Object.entries
withObject.fromEntries
that allows us to use, for example, the.filter
as we want, both the properties and values:To solve it you could iterate through the object
source
to assign its properties excluding'b'
withObject.keys()
andforEach()
as follows:Although it works if you only want to omit one property, to omit more than one you would have to add an array of those that you want to omit and look for those properties not to be included, it could be done with
includes()
:I hope it is what you are looking for, greetings.
How about we add something to your code, removing the elements you don't need from the object:
Posing another point of view, what if we create an Object of what we need and then copy it: