I have a collection of JSON objects with a fixed key 'type' and additional keys based on the type. Here is an example of how it looks:
theArray = [
{
"type": "text",
"text": "= SUM("
},
{
"type": "formula",
"attrs": {
"id": 20,
"data": "Cost",
}
},
{
"type": "text",
"text": ",,"
}
]
After filtering all items where 'type': 'text' like this:
this.theArray.filter(a=>a.type === 'text'))
I am aiming to split each object where type === 'text' so that every character in the text key becomes an item in this.theArray.
Thus, I want to split the above 'type': 'text' object as follows:
theArray = [
{
"type": "text",
"text": "="
},
{
"type": "text",
"text": " "
},
{
"type": "text",
"text": "S"
},
{
"type": "text",
"text": "U"
},
{
"type": "text",
"text": "M"
},
{
"type": "formula",
"attrs": {
"id": 20,
"data": "Cost",
}
},
{
"type": "text",
"text": ","
},
{
"type": "text",
"text": ","
},
]
The first 'type': 'text' object should be split character by character, adding each symbol (such as =, S, U, M) as a new array item with 'type': 'text' and text: that specific character.
I am aware that splitting a string separately requires using .split('')
However, my current approach does not work (only getting the original '= SUM(' object), and I'm uncertain how to proceed further. Does anyone know how to adjust the initial array to match the desired format?
if(theArray.filter(a=>a.type === 'text')) {
theArray.map(a=>a.text).forEach(element => {
element.split('')
theArray.push({type:"text", text: element})
})
}