Having the initial object of this shape:
const initial = { a: 'a', b: 'b', c: 'c', d: 'd', ..., z: 'z' };
The result should contain all properties but without 'b' for example. I know there is a method like
const result = (({ a, b, c, d, ..., z }) => ({ a, c, d, ..., z }))(initial)
but in the case of an object with too many properties it's too much code.
Is there a shorter way to do that?
CodePudding user response:
Clone the object and delete the property:
const result = {...initial};
delete result.b;
CodePudding user response:
Use Object.entries()
to convert the object to an array. Use filter()
to skip that element of the array. Use Object.fromEntries()
to convert that result back to an object.
const result = Object.fromEntries(Object.entries(initial).filter(([key, value]) => key != 'b'))
You can also use destructuring. List all the properties you want to remove explicitly in the destructuring target, then combine the rest into a new object with ...
.
const initial = { a: 'a', b: 'b', c: 'c', d: 'd', z: 'z' };
const {b, ...result} = initial;
console.log(result);
CodePudding user response:
You can copy the object, then delete a key:
const initial = { a: 'a', b: 'b', c: 'c', d: 'd', ..., z: 'z' };
const result = {...initial}; // copy the array
delete result.b;