I have an array of objects like below. Each object has permanent key 'type' and depending on the 'type', new keys are added.
So if type: 'text', we have a new key 'text'.
If type: 'notText', we have a new key 'attrs'.
arrayOfObj = [
{
"type": "text",
"text": "="
},
{
"type": "text",
"text": " "
},
{
"type": "text",
"text": "S"
},
{
"type": "text",
"text": "O"
},
{
"type": "notText",
"attrs": {
"id": 20,
"data": "Something",
}
},
{
"type": "text",
"text": "H"
},
{
"type": "text",
"text": "E"
},
{
"type": "text",
"text": "Y"
},
{
"type": "notText",
"attrs": {
"id": 20,
"data": "Other",
}
},
{
"type": "text",
"text": "="
},
{
"type": "text",
"text": "T"
},
{
"type": "text",
"text": "O"
},
]
The objects are in order, so depending on the 'type' of each item AND the order, then I need to combine them like so:
arrayOfObj = [
{
"type": "text",
"text": "= SO"
},
{
"type": "notText",
"attrs": {
"id": 20,
"data": "Something",
}
}
{
"type": "text",
"text": "HEY"
},
{
"type": "notText",
"attrs": {
"id": 20,
"data": "Other",
}
},
{
"type": "text",
"text": "=TO"
},
]
In summary, whenever 'type' = 'text' then combine every single object with type 'text' that are together. If the next object has type 'notText', then leave it alone until the next item with 'type' = 'text'. Then combine those.
I've asked a previous question that was similar to this with the working answer
let arrayOfObj = [{
"type": "text",
"text": "="
},
{
"type": "text",
"text": " "
},
{
"type": "text",
"text": "S"
},
{
"type": "text",
"text": "O"
},
{
"type": "notText",
"attrs": {
"id": 20,
"data": "Something",
}
},
{
"type": "text",
"text": "H"
},
{
"type": "text",
"text": "E"
},
{
"type": "text",
"text": "Y"
},
{
"type": "notText",
"attrs": {
"id": 20,
"data": "Other",
}
},
{
"type": "text",
"text": "="
},
{
"type": "text",
"text": "T"
},
{
"type": "text",
"text": "O"
},
];
let newThing = arrayOfObj.reduce(
(textKey, typeKey) => {
if (typeKey.type === "text") {
textKey[0].text += typeKey.text;
} else {
textKey.push({
type: typeKey.type,
attrs: typeKey.attrs
});
}
return textKey;
}, [{
type: "text",
text: ""
}]
);
console.log(newThing);
However it combines all instances where 'type' = 'text' regardless or order or other objects with 'type' = 'notText'.
Would anyone have any idea of how to accomplish this?
notTextcomes together then what should happen?type: "text,?