I am combining object values based on the names of the prefixes. All works great except there is a need for separator symbol with array output
const lookup = [
{prefix: "fruit", key: "sweet", "separator": "###" },
{prefix: "rate" }, //noseparator and no key should retain default prefix as rate
];
The above lookup defines which keys must be combined. If the keys are not specified then it means not to combine.
const input = [{
fruit_a: "red apple",
fruit_b: "green apple",
rate_a: "10$",
rate_b: "20$",
vegetable_a: "spinach",
vegetable_b: "carrot",
},
{
fruit_d: "white apple",
fruit_e: "yellow apple",
rate_d: "10$",
rate_e: "20$",
vegetable_d: "radish",
vegetable_e: "cabbage",
}
];
const reduced = Object.entries(input)
.reduce( (acc, [key, value]) => {
const nwKey = lookup.find(v => key.startsWith(v.prefix));
return nwKey
? { ...acc, [nwKey.key]: (acc[nwKey.key] || []).concat(value) }
: { ...acc, [key]: value };
}, {}
);
My incorrect code output is
{
"sweet": [
"red apple",
"green apple"
],
"ratex": [
"10$",
"20$"
],
"vegetable_a": "spinach",
"vegetable_b": "carrot"
}
expected output is
[{
"sweet": "red apple###green apple",
"rate": "10$,20$", //retain default prefix if not mentioned in lookup
"vegetable_a": "spinach",
"vegetable_b": "carrot"
}
{
"sweet": "white apple###yellow apple",
"rate": "10$,20$",//retain default prefix if not mentioned in lookup
"vegetable_a": "radish",
"vegetable_b": "cabbage"
}]