[英]javascript array - separate values and values of values by single quotes
I have an array that looks like this: 我有一个看起来像这样的数组:
var array = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"]
I want to return the results like this: 我想返回这样的结果:
'Rock Paper','Shoot','Dulce','Once','Apple Mic','Chairs'
This is what I have done so far: 到目前为止,这是我所做的:
includes = tagsI.map(tag => `'${tag}'`).join(',')
But this only separates by commas and single quotes the values.. not the values of the values as well. 但这仅以逗号分隔,并用单引号引起来..也不是值的值。
How can I do this? 我怎样才能做到这一点?
Thank you 谢谢
Join the items of the array to a single string with commas. 用逗号将数组的项目连接到单个字符串。 Split the string by the comma separators, map the items to the required format, and join again with commas. 用逗号分隔符分割字符串,将项目映射为所需的格式,然后再次用逗号连接。
const array = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"] const result = array .join(',') .split(',') .map(tag => `'${tag}'`) .join(','); console.log(result);
split tag
by comma and use another map 用逗号分隔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)
How about using reduce : 如何使用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;
<body> <p id="res1"></p> <p id="res2"></p> </body>
The principle is the following : 原理如下:
We have an initial Array "array" in which we stored strings (["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"]) 我们有一个初始数组“ array”,其中存储了字符串([[Rock Paper,Shoot,Dulce“,” Once,Apple Mic,Chairs“])
For each string in the array: 对于数组中的每个字符串:
PS: If you want an array instead of a string, just remove the join(",")
PS:如果要使用数组而不是字符串,只需删除join(",")
You'll first need to split each element in the array. 首先,您需要拆分数组中的每个元素。
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(",");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.