【发布时间】:2021-09-20 05:14:04
【问题描述】:
我有一个 json 对象数组,其中每个对象都有永久键“类型”和其他键,具体取决于类型。看起来是这样的:
theArray = [
{
"type": "text",
"text": "= SUM("
},
{
"type": "formula",
"attrs": {
"id": 20,
"data": "Cost",
}
},
{
"type": "text",
"text": ",,"
}
]
我已经过滤了所有 "type": "text" 的项目,如下所示:
this.theArray.filter(a=>a.type === 'text'))
我正在尝试拆分 type === 'text' 的每个对象,以便 text 键内的每个字符都是 this.theArray 中的一个项目。
所以在这个。 theArray 上面 where "type": "text" 我想把它拆分成如下:
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": ","
},
]
第一个文本类型的对象被拆分按字符顺序,这样每个 =, ,S,U,M,( 都作为“type”数组中的新项添加: “文本”和文本:那个项目。
我知道要单独拆分字符串我需要使用 .split('')
但是这是我到目前为止所拥有的,它不起作用(我只是得到 = SUM() 的原始 json 对象,我不确定如何走得更远。有人会知道编辑第一个数组以显示第二个数组的方法吗?
if(theArray.filter(a=>a.type === 'text')) {
theArray.map(a=>a.text).forEach(element => {
element.split('')
theArray.push({type:"text", text: element})
})
}
【问题讨论】:
-
如果你不使用回调函数的返回值,你应该使用
forEach(),而不是map()。 -
您不应该添加到您正在映射的数组中。将结果放入一个新数组中。
标签: javascript arrays json string split