我有一个如下所示的数组:
@for (int i = 0; i < Model.AllFeatures.Count; i++)
{
<tr>
<td>
@Html.TextBoxFor(model => model.AllFeatures[i].Id)
</td>
<td>
@Html.TextBoxFor(model => model.AllFeatures[i].Name)
</td>
<td>
@Html.EditorFor(model => model.AllFeatures[i].IsActive)
</td>
</tr>
}
我想这样返回结果:
var array = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"]
这是我到目前为止所做的:
'Rock Paper','Shoot','Dulce','Once','Apple Mic','Chairs'
但是这只用逗号和单引号分隔值..而不是值的值。
我该怎么做?
谢谢
答案 0 :(得分:2)
使用逗号将数组的项连接到单个字符串。用逗号分隔符拆分字符串,将项目映射到所需格式,然后再用逗号连接。
const array = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"]
const result = array
.join(',')
.split(',')
.map(tag => `'${tag}'`)
.join(',');
console.log(result);
&#13;
答案 1 :(得分:1)
用逗号分割tag
并使用其他地图
var tagsI = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"]
var result = tagsI.map(tag => tag.split(',').map(tag => `'${tag}'`)).join(',');
console.log(result)
&#13;
答案 2 :(得分:1)
如何使用reduce:
var array = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"];
//V1 : compatible with all browsers
var result = array.reduce((acc, elem, index, arr)=>{
var n_arr = elem.split(",").map(map_elem=> `'${map_elem}'`);
n_arr.forEach(fe_elem => acc.push(fe_elem));
return acc;
}, []).join(",");
console.log(result);
document.querySelector("#res1").innerHTML = result;
//V2: compatible with some browsers
var result2 = array.reduce((acc, elem, index, arr)=>{
var n_arr = elem.split(",").map(map_elem=>`'${map_elem}'`);
acc.push(...n_arr);
return acc;
}, []).join(",");
console.log(result2)
document.querySelector("#res2").innerHTML = result2;
&#13;
<body>
<p id="res1"></p>
<p id="res2"></p>
</body>
&#13;
原则如下:
我们有一个初始的Array&#34;数组&#34;我们存储了字符串([&#34; Rock Paper,Shoot,Dulce&#34;,&#34;一次,Apple Mic,Chairs&#34;])
对于数组中的每个字符串:
PS:如果你想要一个数组而不是一个字符串,只需删除join(",")
答案 3 :(得分:0)
您首先需要拆分数组中的每个元素。
var array = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"];
var split = array.map(v => v.split(","));
var flattened = [].concat.apply([], split);
var str = flattened.join(",");