Given the following
[{ a: 5, b: 2 }, { a: 2, b: 5 }].map(x => {
return {
...x,
b: undefined
}
})
I would like to end up with something like
[{a:5},{a:2})
Is that possible? I know I could do something like
[{ a: 5, b: 2 }, { a: 2, b: 5 }].map(x => {
const obj = {
...x,
}
delete obj.b
return obj
})
or
[{ a: 5, b: 2 }, { a: 2, b: 5 }].map(x => {
return {
a: x.a
}
})
The first method results in the values just being set to "undefined". The second method seems wasteful for larger arrays as a new variable is created object, and also my typescript complains about it because the original property wasn't optional. The third method works if you only want to retain a small number of properties, but once it gets over just a few properties it just seems unwieldy. For my current case, I'll probably opt for the second method, but I am curious if there's a way to handle this more elegantly.
I'm aware that I can also do something like:
Object.keys(obj).forEach(key => obj[key] === undefined && delete obj[key])
But it still doesn't seem all that elegant.
You can just ignore the b and collect all properties in rest and then spread the rest in the final result.
You can also make it one liner
const result = arr.map(({ b, ...rest }) => rest);
const arr = [
{ a: 5, b: 2 },
{ a: 2, b: 5 },
]
const result = arr.map(({ b, ...rest }) => rest);
console.log(result);