How can I remove an property from an array? I wish to remove the property that includes:
someObject = { number: '1', month: 'march', year: '2023' }
And I have an array:
someArray = ['month', 'year'] or a string 'month, year'
And want to extract so that I get:
finalObject = { month: 'march', year: '2023' }
3
Answers
To remove an object from an array based on specific properties, you can use the filter() method along with the includes() method. Here’s how you can achieve the desired result:
In this code, we first define the someObject and someArray variables as provided. Then, we convert the someArray string to an array if it is in string format.
Next, we use Object.keys() to get an array of keys from someObject. We filter this array based on whether the properties in propertiesToRemove are present using the includes() method. Then, using reduce(), we create a new object finalObject by iterating over the filtered keys and assigning the corresponding values from someObject to the finalObject.
Finally, we log the finalObject to the console, which will contain only the properties specified in someArray or someArray string.
Note: The code assumes that the properties to remove exist in someObject. If there’s a possibility that some properties might not exist in someObject, you can add additional checks to handle such cases.
loop over
keys and values
withObject.entries
with the help offilter
to let only keys that exist inpropertiesToExtract
and turn them back into object withObject.fromEntries
We can write a function that maps your keys into
[key, value]
subarrays, using the initial object to extract the values, then useObject.fromEntries
to combine these into a new object:Update
A comment asked to include only those keys whose values actually appear in the original object. This is only a minor tweak: