I have a dataset something like the below.
[
{-a: '-ess. (form feminine singular nouns.)'},
{-a: '(form the feminine singular adjectives.)'},
{-a: '(form the second-person singular.)'},
{-aba: 'first-person singular'},
{-aba: 'third-person singular'},
...
]
I want to have an object that has to be converted to the format of a single object, like the below.
{
-a: '(form the second-person singular.)',
-aba: 'third-person singular',
...
}
The above is a result of Object.assign({}, ...array).
But something is missing here, yep, some data has been trimmed accidentally from the original data above. This is not an desired result.
Now I have an obj that has a merged (in some way) value in the each key. The following is an example I would prefer.
{
-a: '-ess. (form feminine singular nouns.)\n(form the feminine singular adjectives.)\n(form the second-person singular.)',
-aba: 'first-person singular\nthird-person singular',
...
}
So how can I achieve this? Thanks.
You can use Array.reduce(...) on your data and then loop over each object to add them to the reduced value accordingly.
Also, your original array needs some "quotes" on the object keys, otherwise it won't run:
const DATA = [
{"-a": '-ess. (form feminine singular nouns.)'},
{"-a": '(form the feminine singular adjectives.)'},
{"-a": '(form the second-person singular.)'},
{"-aba": 'first-person singular'},
{"-aba": 'third-person singular'},
];
const merge = (data) => {
// reduce the array down to a single object
return data.reduce((acc, curr) => {
// loop over the entries of each object
Object.entries(curr).forEach(([key, value]) => {
// if this key already exists, append to it with \n
if(acc[key] != null) {
acc[key] += `\n${value}`;
// else, just add it as is
} else {
acc[key] = value;
}
});
return acc;
}, {});
}
console.log(merge(DATA));
You could do something like:
const input = [
{ "-a": '-ess. (form feminine singular nouns.)' },
{ "-a": '(form the feminine singular adjectives.)' },
{ "-a": '(form the second-person singular.)' },
{ "-aba": 'first-person singular' },
{ "-aba": 'third-person singular' }
];
// option 1: store values in array
const output1 = input.reduce((outObj, item) => {
const [key, value] = Object.entries(item)[0];
if (outObj[key]) {
outObj[key].push(value);
} else {
outObj[key] = [value];
}
return outObj;
}, {});
console.log(output1);
// option 2: store values in a single string
function myFunc(arr, separator) {
return arr.reduce((outObj, item) => {
const [key, value] = Object.entries(item)[0];
if (outObj[key]) {
outObj[key] += `${separator}${value}`;
} else {
outObj[key] = value;
}
return outObj;
}, {});
}
const output2a = myFunc(input, '\n');
const output2b = myFunc(input, ' | ');
console.log(output2a);
console.log(output2b);