I am trying to group related JavaScript objects in an array by key.
But, I'm at stuck at a point.
I have a JavaScript object array something like this:
[
{
"text": "hello world",
"startPos": 0,
"endPos": 12,
"value": "hello world",
"entity": "Greeting"
},
{
"text": "hello world",
"startPos": 0,
"endPos": 6,
"value": "hello",
"entity": "Greeting"
}
]
I made the following code, but I was stuck.
a = [
{
"text": "hello world",
"startPos": 0,
"endPos": 12,
"value": "hello world",
"entity": "Greeting"
},
{
"text": "hello world",
"startPos": 0,
"endPos": 6,
"value": "hello",
"entity": "Greeting"
}
]
let result = a.reduce((acc, d) => {
const found = acc.find(a => a.text == d.text);
const entitiesArray = {
startPos: d.startPos,
endPos: d.endPos,
entity: d.entity
};
if (found) {
found.entities.push(entitiesArray);
} else {
acc.push({});
}
return acc;
}, []);
console.log(JSON.stringify(result, undefined, 4));
The JavaScript object are being repeated based on the "text" key. I want to group the above array into one object based on the "text" key.
Something like this:
[
{
"text": "hello world",
"entities": [
{
"startPos": 0,
"endPos": 12,
"value": "hello world",
"entity": "Greeting"
},
{
"startPos": 0,
"endPos": 6,
"value": "hello",
"entity": "Greeting"
}
]
}
]
"text": "hello world"in second object? Or is it copy paste issuetextand the second entity has noentity?textkey is same, I want to group them.