I have an array of objects which I need to parse in some way. The objects have a set of common fields and some optional fields that aren't present in all objects. For the sake of the example, a,b,c are common fields and d,e,f are optional. I want to perform some action on some of the fields, e.g double the value of a and capitalize d, while leaving the rest as they were. If an object was missing one or more of the optional fields, it should remain so in the result.
The catch is that I want to do it in a purely functional way, without declaring an empty array and pushing into it.
Example input:
const input = [
{
a: 3,
b: 'test',
c: 34,
d: 'example'
},
{
a: 6,
b: 'another',
c: 0,
e: true,
f: () => {}
}
];
Expected result:
[
{
a: 6,
b: 'test',
c: 34,
d: 'EXAMPLE'
},
{
a: 12,
b: 'another',
c: 0,
e: true,
f: () => {}
}
]
What I tried so far was using map like so:
const result = input.map(x => ({
a: 2 * x.a,
d: x.d.toUppercase()
});
Or like so:
const result = input.map(x => ({
a: 2 * x.a,
b,
c,
d: x.d.toUppercase(),
e,
f
});
But this results in objects that either contain only the fields which were manipulated, or all of them, regardless if they existed in the original object.
Any suggestions on how to accomplish that?